0

I have a jquery on some checkboxes and I am trying to serialize the values so I can get multiple selections in a PHP.

Here is my jquery:

<script type="text/javascript">
    jQuery(document).ready(function($) {
        $("input:checkbox").change(function() {
            if($(this).is(':checked')) 
            {
                    var color = $(this).val().serialize;
                    $(".itemMain").hide();
                    $(".indexMain").load('indexMain.php?color='+color);
            }
        });
    });
</script>

And here my PHP:

$color = $_GET['color'];

Before applying th serialize, everything was working fine but I couldn't have multiple selections. Now it just doesn't work at all with the serialize().

Any suggestions? Thanks!

3
  • 1
    since $(this).val() will always return one value, I don't see why you need serialize ? Commented Aug 5, 2012 at 4:08
  • 1
    You can't serialize a checkbox's value, as the returned value isn't a jQuery object. Also, you aren't actually calling serialize(), as you forgot the parentheses.
    – Blender
    Commented Aug 5, 2012 at 4:12
  • I actually need to serialize if multiple boxes are checked. How would I do it?
    – samyb8
    Commented Aug 5, 2012 at 11:32

2 Answers 2

1

Another solution that worked for me.

Simply specified in the name attribute of your field that you want a multiple value in other terms : an array

<form action="" method="post" id="filters_form"">
    <input id="fieldNameText" value="value0" name="fieldNameText" type="text">                                  
    <input type="checkbox" name="myFieldName[]" id="myFieldName" value="value1"/>
    <input type="checkbox" name="myFieldName[]" id="myFieldName" value="value2"/>
</form>

The serialize() method var dataString = $("#filters_form").serialize(); will result in

fieldNameText=value0&myFieldName%5B%5D=value1&myFieldName%5B%5D=value2

If you send those data in post with AJAX you'll get this in php :

Ajax

$.ajax({
    type: "POST",
    url: "yourFormURL",
    data: dataString,
    success: function(response) {
        //do something
    }
});

PHP

print_r($_POST);

/* Output :
Array ( [fieldNameText] => value0 [myFieldName] => Array ( [0] => value1 [1] => value2 )) 
*/
0

Rough solution can be, on click event of each checkbox you can store/append its value in a variable(or a hidden input field) in a comma separated form, and pass this variable to the color query string.

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