jeudi 30 novembre 2017

Not able to remove values from array after uncheck in checkboxes

I have a requirement where all the checked values in checkboxes should be displayed in a textarea. This part works perfectly fine,but the problem occurs when i uncheck the checkbox unchecked element is not getting removed from the array. i have used jquery each function as shown within double quotes.

"$("input:checkbox[name=category]:checked").each(function(){"

As per my understanding,the above function will check for only checked values and updates into the array,so if any value is unchecked and this function is called,the unchecked value should be removed isn't it?

var pc = [];
function check(){
$("input:checkbox[name=category]:checked").each(function(){
             pc.push(decodeURI($(this).val()));
    });
         pc = $.unique(pc);
    document.getElementById("result").value = pc.join("\n");
}
<script src="http://ift.tt/1qRgvOJ"></script>
<body onload ="check()">
<input type="checkbox" name="category" value="a/b" onclick="check()" checked>
<input type="checkbox" name="category" value="c/d" onclick="check()" checked>
<input type="checkbox" name="category" value="e/f" onclick="check()" checked>
<input type="checkbox" name="category" value="g/h" onclick="check()" >

<textarea id="result"></textarea>

The above snippet highlights the issue,where if i uncheck any checkbox,the value is not getting removed from array. Please correct me if i am doing anything wrong? Please help me! Thanks in advance




Aucun commentaire:

Enregistrer un commentaire