Reputation: 161
I have a checkbox in each row. I have a button which deletes all the rows in which the check boxes are checked. For that, I have to get id of the rows where the checkbox is checked.I have written the following code. But not working. Pls help me out guys..
Button code : <a class="row-delete" align="left" onclick="deleteItem()"/>
function deleteItem(){
if (confirm("Are you sure you want to delete?")){
$(":checkbox").change(function() {
var notChecked = [], checked = [];
$(":checkbox").map(function() {
this.checked ? checked.push(this.id) : notChecked.push(this.id);
});
alert("checked: " + checked);
});
deleteAll(checked,0);
}
}
What is wrong in above code?
Upvotes: 0
Views: 7013
Reputation: 40639
Remove onchange function
from deleteItem
because when you click
on link
it will re-init
on change of checkbox elements
function deleteItem(){
if (confirm("Are you sure you want to delete?")){
var notChecked = [], checked = [];
$(":checkbox").each(function() {
id=this.id;
this.checked ? checked.push(id) : notChecked.push(id);
});
alert("checked: " + checked);
deleteAll(checked,0);
}
}
You can create an array of checked checkboxes
like,
$(":checkbox:checked").each(function() {
checked.push(this.id);
});
And if you want to delete items onclick of checkbox then try like,
$(":checkbox").on('click',function() {
if($(this).is(':checked')){
alert($(this).attr('id'));// this item is ready to delete
}
});
Upvotes: 1
Reputation: 388316
You are registering a change
event handler in the deleteItem
method that is not required, you need to just iterate through the checkboxes using .each() and update the required arrays
Also it is preferred to use .each()
instead of .map()
as you are not returning any value
function deleteItem(){
if (confirm("Are you sure you want to delete?")){
var notChecked = [], checked = [];
$(":checkbox").each(function() {
if(this.checked){
checked.push(this.id);
} else {
notChecked.push(this.id);
}
});
alert("checked: " + checked);
deleteAll(checked,0);
}
}
Upvotes: 1