0

I have a checkbox in a page and on page load it is unchecked. When the checkbox is being checked, the value TRUE is being passed correctly, though when the checkbox is remained unchecked on load of the page, the value FALSE is not being passed. I am using the following code to do this.

$(document).ready(function () {
    $('#MemberCountryOptInchkbox').change(function(){
        if($(this).attr('checked')){
              $(this).val('TRUE');
         }else{
              $(this).val('FALSE');
         } 
    });
});
Joe
  • 15,205
  • 8
  • 49
  • 56
Rene Zammit
  • 1,121
  • 5
  • 19
  • 42
  • 2
    This is what your looking for. http://stackoverflow.com/questions/426258/how-do-i-check-a-checkbox-with-jquery-or-javascript – Anil Dec 01 '11 at 11:41

5 Answers5

0

Note that JustAnil's comment points to the perfect answer IMO.

If a checkbox isn't checked, then when a form is posted, nothing is posted - it only get's submitted when the checkbox is checked.

So server side, if there isn't a value for your checkbox in request.forms or similar, then you can assume it isn't checked.

dash
  • 89,546
  • 4
  • 51
  • 71
0

When a checkbox is deselected its value is not passed by the form. If you don't want to check against this behaviour, use an hidden field.

Viruzzo
  • 3,025
  • 13
  • 13
0

Try using click handler instead of change

$('#MemberCountryOptInchkbox').click(function(){
Gautam
  • 7,868
  • 12
  • 64
  • 105
0

Your current implementation attaches the change-handler to your checkbox when the page is loaded. However, this doesn't mean the code is executed on page load. To accomplish that you should have something along the lines of:

$(document).ready(function () {

    $('#MemberCountryOptInchkbox').change(function(){
        if($(this).attr('checked')){
            $(this).val('TRUE');
        }else{
             $(this).val('FALSE');
        }
    });

    if($(this).attr('checked')){
        $(this).val('TRUE');
    }else{
         $(this).val('FALSE');
    }
});

This makes sure the code is also executed once at page load.

Joe
  • 15,205
  • 8
  • 49
  • 56
Pieter
  • 3,339
  • 5
  • 30
  • 63
0

The solution is simple to your problem, you can use the following markup for your check box

<input type="checkbox" value="FALSE">...

This will submit the value "FALSE" to the server if the checkbox is not selected

Kamran Ali
  • 5,904
  • 2
  • 26
  • 36