1

Im trying to send an array of checkboxes (value) to PHP via jquery. How can that be done?

See the following example:

<input type="checkbox" name="option[]" value="0"> Small
<input type="checkbox" name="option[]" value="1"> Medium
<input type="checkbox" name="option[]" value="2"> Large
<input type="checkbox" name="option[]" value="3"> X-Large

<input id="ButtonAdd" type="button" value="Add" />

jQuery code, couldn't get to work:

$("#ButtonAdd").click(function() { 
    var options = $("input:checkbox[name='option[]']");
     $.post("ajax_extras.php", { options:options  },
       function(data)  {
         console.log(data)
    });
});

ajax_extras.php file:

<?php
 print_r($_POST['options']);
?>
3
  • you may need to escape the brackets inside the brackets: var options = $("input:checkbox[name='option\\[\\]']"); Commented Sep 13, 2011 at 19:23
  • @mblase75 i think single slash will escape it ? Commented Sep 13, 2011 at 19:25
  • nope you are right `\\` are needed Commented Sep 13, 2011 at 19:27

2 Answers 2

1

you need to escape the []

var options = $("input:checkbox[name='option\\[\\]']");
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, that work but my browser freeze when it attempting to do ajax or something... I have tried to remove ajax code and it work.. any clue?
by freeze you mean freeze and then unfreeze or just freezes and then craches? may be you are handling a lot of data?
The data is only print_r($_POST['options']); and only few tickboxes
0

Add a class attribute to the checkboxes and do instead:


$("#ButtonAdd").click(function() { 
    var options = $("input[type=checkbox].checks");
     $.post("ajax_extras_add_extras.php", { options:options  },
       function(data)  {
         console.log(data)
    });
});

2 Comments

I dont think input[type=checkbox].checkk would work because I have couple of tickboxes that is not belong with option[] name. I only want to send data to php that has option[] name
Then you place the class wherever you see fit, that's up to you.

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.