【问题标题】:multiple checkbox javascript多个复选框javascript
【发布时间】:2016-10-19 08:05:35
【问题描述】:

我尝试使用 javascript 制作多个复选框,但我的代码不起作用,我的代码总是检查所有框

for(var i=0; i<3; i++){
    document.write("<div class='checkbox'><label><input type='checkbox' value='1' onclick='changeText();' >Item</label></div><input type='text' name='myItem' value='0' disabled/><br/>");
}

var item_box = document.getElementsByName('myItem');
var x;
//alert(item_box.length);
function changeText(){
  for(x=0;x<item_box.length;x++){
   if(item_box[x].hasAttribute('checked')){
    item_box[x].value="0";
    item_box[x].setAttribute('checked', true);
    item_box[x].removeAttribute('checked');
    item_box[x].setAttribute('disabled', false);
   } else {
    item_box[x].value="1";
    item_box[x].setAttribute('checked', false);
    item_box[x].setAttribute('disabled', true);
    item_box[x].removeAttribute('disabled');
   }
  }
}

【问题讨论】:

  • 我真的不明白你的问题是什么,你想做什么以及你想要什么。
  • 我用文本框制作多个复选框,如果我选中了复选框[],则文本框不会禁用我可以流利地使用英语,请尝试我的代码,ty
  • 我更喜欢使用var div = document.createElement("div")document.body.appendChild(div) 而不是document.write。它更干净,更适合代码维护。 MDN | Document.createElement()

标签: javascript arrays codeigniter


【解决方案1】:

    for(var i=0; i<3; i++){
        document.write("<div class='checkbox'><label><input type='checkbox' value='1' onclick='changeText(this,"+i+");' >Item</label></div><input type='text' name='myItem' value='0' disabled/><br/>");
    }
    
    var item_box = document.getElementsByName('myItem');
    
    function changeText(e,i){
    	item_box[i].value = e.checked ? 1 : 0;
    	item_box[i].disabled = !e.checked;
    }

我不明白为什么要投反对票,添加了代码 sn-p。

【讨论】:

  • 它做了它应该做的事情。
【解决方案2】:

下面的代码应该只启用一个输入框。

for(var i=0; i<3; i++){
    document.write("<div class='checkbox'><label><input type='checkbox' value='1' onclick='changeText(this);' >Item</label></div><input type='text' name='myItem' value='0' disabled/><br/>");
}


function changeText(element){
   var inputBox = element.parentElement.parentElement.nextSibling;
    
   if(inputBox.hasAttribute('checked')){
    inputBox.value="0";
    inputBox.setAttribute('checked', true);
    inputBox.removeAttribute('checked');
    inputBox.setAttribute('disabled', false);
   } else {
    inputBox.value="1";
    inputBox.setAttribute('checked', false);
    inputBox.setAttribute('disabled', true);
    inputBox.removeAttribute('disabled');
   }
}

【讨论】:

  • np ;) 确保将此标记为答案,以便在查看问题列表时通知其他人:)
猜你喜欢
  • 2023-03-09
  • 1970-01-01
  • 2015-07-28
  • 1970-01-01
  • 2014-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多