4

so I am trying to implement the Jquery .serializeArray() method to transform a form into a JSON string to send it out in a request. This works great for my form except for checkboxes and radio buttons. The only time this works properly is when they are checked. Sometimes, I need to know if they are unchecked. They still need to get serialized.

I suppose I could manually loop through the form and grab the values and build the JSON object, but that would not be optimal.

According to the Jquery documentation found here: Jquery Docs anything that fits the W3 standards for a successful control found here should get included. Unfortunately, this does not include checkboxes that are not checked. Does anyone have a work around for this behavior? Thanks in advance...


var form = document.getElementById('f');
console.log($(form).serializeArray();

That spits out the serialized form with the checkboxes that are not checked excluded...

gabaum10
  • 3,769
  • 3
  • 48
  • 89
  • Similar to this: http://stackoverflow.com/questions/3029870/jquery-serialize-does-not-register-checkboxes – CAbbott Sep 09 '11 at 19:41
  • Lol, I do, but it's not very interesting. Everything you need to know is up there. I will update it though... – gabaum10 Sep 09 '11 at 20:00

4 Answers4

3

how about trying this, I had a similar problem, I thought unchecked checkboxes should have a value as well, here is a quick work around, add an extra class on each checkbox on your form "cbx" make data an array from the form with serialise

then loop through all checkboxes with a class of "cbx" and add them to the array with a value of 0, AFTER the array has been created with (serializeArray())

when you post the data you will see the unchecked checboxes and values of 0 will get transferred with the post.

    var data = $('#form').serializeArray();

    $(".cbx:not(:checked)").each(function() {
        data.push({name: this.name, value: '0' });
    });

    $.post("testpage.asp", data);
3

An alternative would be to use a jQuery plugin. For example, serializeJSON has the option to set the value for unchecked checkboxes like this:

$('form').serializeJSON({checkboxUncheckedValue: "false"});

In any case, it is usually best to use hidden inputs for unchecked values.

tothemario
  • 5,851
  • 3
  • 44
  • 39
3

If you really want to use checkboxes and radio buttons, have those input fields update a corresponding hidden field. That way, the hidden input will always be sent.

Rolando Cruz
  • 2,834
  • 1
  • 16
  • 24
0

Alright, so I developed a workaround.

Basically I wrote a function to compare the original JSON object to the serialized form. As I looped through, I compared the components. If there was a discrepancy, I pulled the component off the form and manually inserted it into the JSON. I used the array.splice() method to add the missing components. Worked for all of the missing inputs.

gabaum10
  • 3,769
  • 3
  • 48
  • 89