paz
paz

Reputation: 1245

Store diferrent IDs in an Array with jQuery

I'll describe what i wanna do.

I have table which imports the data from database and for every row i have a checkbox with the ID from the database(primary key). It looks like this.

cb = checkbox

cb id=1 | name | content | bla bla

and so on.

I am able to delete 1 row at a time, but i want to delete multiple rows by checking multitple cheboxes and press the delete button. I was thinking of storing those checkboxes ids into and array once you check any of them and then do a loop when i press the button to delete the selected ones.

My single delete button code looks like this(this button use it's own ID to delete, which is the same with the checkbox on the same row):

$('.del').click(function(){
var myid = $(this).attr('id');
$.post('newsdel.php', {delete_id:myid}, function(data) {
    if(data == 'true') {
        $('#'+myid).fadeOut();
        var rowCount = $('#count tr').length;
        if(rowCount < 3) {
        window.location = '?news=1';
        }
        } else {
        alert('Could not delete!');
        }
    });
});

Upvotes: 0

Views: 141

Answers (2)

Nikola Kirincic
Nikola Kirincic

Reputation: 3757

This is just one of solutions:
First add to each checkbox css class like: "checkbox-option" to delete button add css class 'delete-btn'

Then this jQuery code:

 $('.delete-btn').click(function(){
      $('.checkbox-option').each(function(){
      if($(this).is(':checked'){
      //then goes larger part of your code: 
      var myid = $(this).attr('id');
        $.post('newsdel.php', {delete_id:myid}, function(data) {
         if(data == 'true') {
            $('#'+myid).fadeOut();
            var rowCount = $('#count tr').length;
            if(rowCount < 3) {
            window.location = '?news=1';
            }
            } else {
            alert('Could not delete!');
            }
         });
      }

       });
    });

This was in case when using your part of code, but it sends ajax request for each. Other would be instead, while iterating, to collect all ids in array ( and then serialize) or separate by comma sign ( and then split in server side script), and then send one ajax request.

Upvotes: 0

vipulsharma
vipulsharma

Reputation: 1252

considering your checkboxes have class checkbox

function getCheckedRows() {
var checkedRows = [];
  $('.checkbox').each(function() {
      if($(this).is(':checked')) {
          checkedRows.push($(this).attr('id'); //assuming id is the row id 
      } 
  });
return checkedRows;
}
$('.del').click(function(){
var rowIds = getCheckedRows();
for(var myid in rowIds) {
   $.post('newsdel.php', {delete_id:myid}, function(data) {
    if(data == 'true') {
        $('#'+myid).remove();
        var rowCount = $('#count tr').length;
        if(rowCount < 3) {
        window.location = '?news=1';
        }
        } else {
        alert('Could not delete!');
        }
    });
}
});

Upvotes: 1

Related Questions