Reputation: 519
I have a list of categories paired with checkboxes. I can't find any documentation on how to store all the selected checkboxes in a var and send the data to the server. I need to delete from the database the selected categories. This is part of the code I'm working on.
var cat_id = $('check_box').attr("id"); //gets the id of the checked category
var dataString = 'cat_id=' + cat_id; //should send all the selected checkbox IDs
$('.delete').click(function()
{
$.ajax({
type: "POST",
url: "edit_categories.php",
data: dataString,
cache: false,
success: function(html)
{
window.location.reload(true);
}
});//end ajax
});//end click function
The checkboxes are created dynamically using:
<input type="checkbox" name="check_box" class="check_box"
id="<?php echo $cat_id; ?>" />
Each checkbox will have a unique id and how many they are varies.
In the edit_categories.php I just have an mysql for deleting the categories where cat_id = $_POST['cat_id'] but I can't figure out how to get all the IDs from the selected checkboxes.
Upvotes: 0
Views: 3253
Reputation: 630349
You can use .map()
to get a string of checkbox IDs, like this:
var cat_id = $(':checkbox:checked').map(function() {
return this.id;
}).get().join(',');
This would produce a string like "CheckBox1,Checkbox2,Checkbox3"
for sending server-side. There you can just do a .split(",")
on the string to get an array of the IDs to work with.
Upvotes: 3
Reputation: 9548
Try something like this:
var keysToDelete = '';
$('.check_box:checked').each(function() {
keysToDelete+= $(this).attr("id");
});
dataString= 'cat_id='+keysToDelete;
// continue down to the ajax post
Upvotes: 0
Reputation: 6573
$('form').serialize() may be of use - have a look at ajaxForm which is awesome...
for your check boxes - change the name to 'check_box[]' and set the value to the cat_id as opposed to its ID.
you should then be able to access $_POST['cat_id] which should be an array of the posted values. check it using var_dump( $_POST['cat_id'] );
Upvotes: 0