简体   繁体   中英

Get Checkbox total count & save value in textbox if checked

I have written below code to get a total count of Checked chechbox and save the value checked value comma separated in textbox.

HTML:

<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='1' onchange='checkCount(this.value);'></label>
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='2' onchange='checkCount(this.value);'></label>
<label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='3' onchange='checkCount(this.value);'></label>

<input type="text" name="proId" id="proId">

JS:

function checkCount(elm) {
  var cheCount = $(":checkbox:checked").length;
  document.getElementById('selectCount').innerHTML = cheCount;

  definVal = document.getElementById('proId').value ;
  var inval = elm+","+definVal;
  document.getElementById('proId').value = inval;

  if(cheCount==0){
    document.getElementById('proId').value = "";
  }
}

Check the output in below image: 在此处输入图片说明

My issue is that, when i unchecked the checkbox, its value is adding in textbox instead of getting remove.

Make below changes, just call js method dont send its value

And then check by their classname

 function checkCount(elm) { var checkboxes = document.getElementsByClassName("checkbox-btn"); var selected = []; for (var i = 0; i < checkboxes.length; ++i) { if(checkboxes[i].checked){ selected.push(checkboxes[i].value); } } document.getElementById("proId").value = selected.join(); document.getElementById("total").innerHTML = selected.length; } 
 <label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='1' onchange='checkCount();'></label> <label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='2' onchange='checkCount();'></label> <label class='checkbox-inline'><input type='checkbox' class='checkbox-btn' value='3' onchange='checkCount();'></label> <input type="text" name="proId" id="proId"> <div>Total Selected : <span id="total">0</span></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM