views:

50

answers:

3

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.

A: 

$('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'] );

ToonMariner
thanks! I'll try this :) serialize() seems like a handy function
vii
A: 

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
Tahbaza
Cool this works too! Thanks!! Do you know how to put space between the id's? It appears as cat_id=1234567
vii
change this line: keysToDelete+= ","+$(this).attr("id") and then add if (keysToDelete.length > 0) keysToDelete = keysToDelete.substr(1); after the end of the each function.
Tahbaza
+1  A: 

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.

Nick Craver
It works! Thanks so much! :)
vii