Reputation: 435
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.
Upvotes: 1
Views: 1335
Reputation: 34914
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>
Upvotes: 2