Rizaldy Setiawan H
Rizaldy Setiawan H

Reputation: 105

multiple checkbox javascript

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

Upvotes: 0

Views: 251

Answers (2)

Mamdouh Saeed
Mamdouh Saeed

Reputation: 2324

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

Upvotes: 4

Deividas
Deividas

Reputation: 6507

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

Upvotes: 1

Related Questions