How to GetChecked values and Remove unchecked in array
10,138
Solution 1
The approach you've taken could be very tedious. You could use .map()
you can re-evaluate the array every time a checkbox is checked or unchecked as follows:
$(':checkbox[name=test]').on('change', function() {
var assignedTo = $(':checkbox[name=test]:checked').map(function() {
return this.id;
})
.get();
//Out for DEMO purposes only
$('pre.out').text( JSON.stringify( assignedTo ) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="test" value="1" id="c1"/> 1 <br/>
<input type="checkbox" name="test" value="2" id="c2"/> 2 <br/>
<input type="checkbox" name="test" value="3" id="c3"/> 3 <br/>
<input type="checkbox" name="test" value="4" id="c4"/> 4 <br/>
<input type="checkbox" name="test" value="5" id="c5"/> 5 <br/>
<input type="checkbox" name="test" value="6" id="c6"/> 6 <br/>
<input type="checkbox" name="test" value="7" id="c7"/> 7 <br/>
<!--output area for DEMO purposes only -->
<pre class="out"></pre>
Solution 2
why not clear the array and store it with new values
var values=[];
$(".cbx").click(function(){
values=[];
$(".cbx").each(function(){
if($(this).is(":checked"))
values.push($(this).val());
});
alert(values);
});
or
var values=[];
$(".cbx").change(function(){
if($(this).is(":checked"))
values.push($(this).val());
else{
var x = values.indexOf($(this).val());
values.splice(x,1);
}
alert(values);
});
Author by
Mohsin Khan
Updated on August 02, 2022Comments
-
Mohsin Khan almost 2 years
i use array for checkbox value, if i click on checkbox it gets values,and if i uncheck this checkbox it remove its value and not save in array,here is my Code..
function selectUser(sender) { if (sender.prop('checked'),true) assignedTo[assignedTo.length] = sender.id; else { for (var i = 0; i < assignedTo.length; i++) { if (sender.id == assignedTo[i]) { assignedTo.splice(i, 1); break; } } } }
Now My issue is if checked it saves value and if i uncheck it did not remove value from array,any help