0

I try to make multiple checkbox with javascript, but my code is not working, my code always checks all boxes

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');
   }
  }
}

3

2 Answers 2

4

    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;
    }

Sign up to request clarification or add additional context in comments.

1 Comment

Please explain this snippet with the intent to educate.
1

The code below should enable only one input box as you want to.

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');
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.