javascript
  • html
  • checkbox
  • 2009-05-14 15 views 33 likes 
    33

    次のHTML/JavaScriptを使用して動的にチェックボックスを作成しようとしています。なぜそれが動作しない任意のアイデア?JavaScriptを使用してチェックボックスを動的に作成しますか?

    <div id="cb"></div> 
    <script type="text/javascript"> 
        var cbh = document.getElementById('cb'); 
        var val = '1'; 
        var cap = 'Jan'; 
    
        var cb = document.createElement('input'); 
        cb.type = 'checkbox'; 
        cbh.appendChild(cb); 
        cb.name = val; 
        cb.value = cap; 
        cb.appendChild(document.createTextNode(cap)); 
    </script> 
    

    答えて

    80

    入力ノード内にテキストノードを配置しようとしています。

    入力要素は空で、子を持つことはできません。あなたが関数を作成することができます

    ... 
    var checkbox = document.createElement('input'); 
    checkbox.type = "checkbox"; 
    checkbox.name = "name"; 
    checkbox.value = "value"; 
    checkbox.id = "id"; 
    
    var label = document.createElement('label') 
    label.htmlFor = "id"; 
    label.appendChild(document.createTextNode('text for label after checkbox')); 
    
    container.appendChild(checkbox); 
    container.appendChild(label); 
    
    +6

    IEのいくつかのフレーバでは、コントロールがページに追加された後に設定しない限り、checkbox.checkedの値は固定されません。 –

    3

    最後の行は、チェックボックスと同じコンテナにテキスト(?ラベル)を追加

    cbh.appendChild(document.createTextNode(cap)); 
    

    を読むべきではなく、チェックボックス自体

    0

    function changeInputType(oldObj, oTyp, nValue) { 
        var newObject = document.createElement('input'); 
        newObject.type = oTyp; 
        if(oldObj.size) newObject.size = oldObj.size; 
        if(oldObj.value) newObject.value = nValue; 
        if(oldObj.name) newObject.name = oldObj.name; 
        if(oldObj.id) newObject.id = oldObj.id; 
        if(oldObj.className) newObject.className = oldObj.className; 
        oldObj.parentNode.replaceChild(newObject,oldObj); 
        return newObject; 
    } 
    

    あなたは次のような電話をします:

    changeInputType(document.getElementById('DATE_RANGE_VALUE'), 'checkbox', 7); 
    
    関連する問題