Neta Meta
Neta Meta

Reputation: 4047

getting the value of multiple checkboxes and using ajax to preform an action with their values

I have a table that has checkboxes, if a checkbox is selected i want a raw in the DB to be deleted - using ajax.

with normal form i would simply name all the chexboxs some name lets say name="checkbox[]" and then simply use foreach($_POST['checkbox'] as $value){}

now i am trying to get all the values of marked checkboxes then put them into an array. seems i am missing something though. here is what i go so far:

var checkboxes = jQuery('input[type="checkbox"]').val();
var temp = new Array();
jQuery.each(checkboxes, function(key, value) { 
     temp[] = value;
});

Late on i will just pass temp as variable to ajax call.

Is there anything i am missing ?

Upvotes: 1

Views: 1965

Answers (3)

Joel Mellon
Joel Mellon

Reputation: 3855

Just wrap the table in a form tag, and do this:

var myData = jQuery('#myform').serialize();
jQuery.ajax('myscript.php', {data:myData});

Upvotes: 0

Ram
Ram

Reputation: 144679

You can use :checked selector and map method:

var arr = $('input[type="checkbox"]:checked').map(function(){
     return this.value
}).get();

Upvotes: 3

Sushanth --
Sushanth --

Reputation: 55740

You are trying to iterate over the Checkbox values which is wrong . Try this

var $checkboxes = jQuery('input[type="checkbox"]') ;
var temp = new Array();
jQuery.each($checkboxes, function(i) {
     var value = $(this).attr('value'); 
     temp[i] = value;
});

If you want to pass only checked items just add a condition.

if($(this).is(':checked')){
  var value = $(this).attr('value'); 
  temp[i] = value;
}

Upvotes: 0

Related Questions