1

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 ?

1
  • Note that JavaScript is not Java. Commented Oct 24, 2012 at 23:51

3 Answers 3

3

You can use :checked selector and map method:

var arr = $('input[type="checkbox"]:checked').map(function(){
     return this.value
}).get();
Sign up to request clarification or add additional context in comments.

6 Comments

What is the purpose of the chained .get()? .map will return an array.
@MattStone map returns a jquery-wrapped array, get returns the actual array.
are you sure about that? The documentation (api.jquery.com/jQuery.map) or a quick test (jsfiddle.net/2aSdZ) doesn't indicate that's the case.
@MattStone Yes, what you are using is $.map utility function and I have used this map api.jquery.com/map
@MattStone See this jsfiddle.net/k96VX without get you will have TypeError: arr.join is not a function
|
0

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;
}

1 Comment

Check out jQuery.map(), it's a better fit for this task than jQuery.each().
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.