Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get proper checkbox value using form.serialize

We are currently using $('form').serialize() to get all form information

This will return any checkbox values as "On" or "Off".

Is there any way to get a 1/0 or true/false value using this same method?

like image 462
Theun Arbeider Avatar asked Jul 23 '13 11:07

Theun Arbeider


3 Answers

Yes. You can do it by adding a hidden input with the same name as checkbox which value will be submitted if checkbox is unchecked:

<input type="hidden" name="option" value="false"/>
<input type="checkbox" name="option" value="true"/>

It will submit both values if checkbox is checked. But server side will read the latest one (value of checkbox)

like image 163
Konstantin Rudy Avatar answered Nov 08 '22 21:11

Konstantin Rudy


The value of a form control is always a string. You can use radio buttons to get different values for the same control name:

<form ...>
  <input type="radio" name="whatever" value="true">true
  <br>
  <input type="radio" name="whatever" value="false">false
  ...
</form>

Only one can be checked, and only the checked name/value will be sent to the server.

like image 1
RobG Avatar answered Nov 08 '22 21:11

RobG


If we have multiple checkboxed in our page like :

  <input id="reminder" name="Check1" value="false" type="checkbox" /> 

  <input id="alarm" name="Check2" value="false" type="checkbox" />

we have to bind the change event of these checkboxes and set its value to true or false.

 $('input[type=checkbox]').on('change', function(){
    var name =    $(this).attr('name');
    if($(this).is(':checked')){
    $('input[name= "' +name +'"]').val(true);
        $(this).val(true);
    }
    else{
       $(this).val(false);
       $('input[name= "' +name +'"]').val(false);
    }
});

By default, checkbox value doesn't appear in $('form').serializeArray(), It appears when it is checked.

We have to keep one hidden field for each checkbox like :

<input type="hidden" value="false" name="Check1" />
<input type="hidden" value="false" name="Check2" />

Now when we serialize the form now, we get the correct value like : Check1=true Check2=false

like image 1
Rajdeep Avatar answered Nov 08 '22 21:11

Rajdeep