1

On a page, I have several checkboxes, the id is different for each. The number of checkbox is not fixed, may be one, 4, 10, ... I'd like get all the id and send them via a $.post.

How can I do this ?

Thanks,

Update 1:

var jqxhr = $.post("/Controller/MyAction", {
    field1: $("#field1").val(),
    benefic: $(":checkbox").serialize(),
    fileld2: $("#fileld2").val()
},
function (data) {
})
.success(function () {
})
.error(function (jqXHR, status, error) {
})
.complete(function () {

});

I don't see any value in my controller for "benefic" ... and it's the "id" of selected checkbox I need

3 Answers 3

6

Do this:

$.post('your_url', $(":checkbox").serialize() );

If your checkboxes have the same name, for example name="myCheckbox[]", you could do this:

$.post('your_url', $(":checkbox[name='myCheckbox[]']").serialize() );

Hope this helps.

EDIT: Solution for your Update 1:

$.post("/Controller/MyAction", {
    field1: $("#field1").val(),
    benefic: $(":checkbox:checked").attr("id"),
    fileld2: $("#fileld2").val()
},
...

This will do what you ask for.. but, are you sure it will always be only 1 checkbox. selected? If you need more than 1 (i'm almost sure you do), in which format do you need to send them? Ids separated by commas?

To send all checked ids, separated by commas, you would do this:

$.post("/Controller/MyAction", {
    field1: $("#field1").val(),
    benefic: $(':checkbox:checked').map(function() { return this.id; }).get().join(','),
    fileld2: $("#fileld2").val()
},
...

Cheers

3
  • I can have several checkbox checked, comma separator is ok
    – TheBoubou
    May 3, 2011 at 8:34
  • Wouldn't it be better if it was an array of ids?
    – Svish
    May 3, 2011 at 13:41
  • The ideal would be sending with name postfix convention [] (as the first code suggested), or send json-encoded. But it depends on the requirements of kris. May 3, 2011 at 15:19
1

I believe something like this would do the trick:

    var json_send = {};
    $("input:checkbox").each(function()
                             {
                                 //Push all the $(this).attr("id") into the Json

                             });
//And here you send them
0

You can use jQuery .serialize() function to get form fields values from your form and then send it through jQuery .post

For Example:

$.post("test.php", $("#testform").serialize());
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.