Reputation: 13
My JavaScript:
<script type="text/javascript">
function getVal(chk, adto)
{
var ad="";
if (chk.checked)
{
ad=document.getElementById(adto).value + chk.value;
document.getElementById(adto).value = ad;
}
else
{
}
}
</script>
The first block is working as I wanted but when user unchecked the check box it should remove the value from the text box.
Below is the HTML code:
<body>
<input type="checkbox" name="chk[]" value="0" id="chk0" onclick="getVal(this, 'inp0')">value 0<br>
<input type="checkbox" name="chk[]" value="1" id="chk1" onclick="getVal(this, 'inp0')">value 1<br>
<input type="checkbox" name="chk[]" value="2" id="chk2" onclick="getVal(this, 'inp0')">value 2<br>
<input type="checkbox" name="chk[]" value="3" id="chk3" onclick="getVal(this, 'inp0')">value 3<br>
<input type="checkbox" name="chk[]" value="4" id="chk4" onclick="getVal(this, 'inp0')">value 4<br>
<input type="checkbox" name="chk[]" value="5" id="chk5" onclick="getVal(this, 'inp0')">value 5<br>
<br>
<input type="text" name="inp" id="inp0" readonly><br>
Please help how to remove the unchecked options from the text box.
Upvotes: 0
Views: 1022
Reputation: 177940
Assuming all checkboxes with the same name adds to the same field. If not we will need more code.
I also assumed the boxes are wrapped in a form tag
function getVal(chk, adto) {
var ad=[];
var checks = chk.form[chk.name];
for (i=0;i<checks.length;i++) {
if (checks[i].checked) {
ad.push(checks[i].value);
}
}
document.getElementById(adto).value = (ad.length>0)?ad.join(" "):"";
}
Upvotes: 1