0

A common practice for checkboxes is to pair it with a hidden field, which will ensure that the HTTP post always includes a value even when the checkbox is left unchecked.

For example, if I have a terms checkbox, I might implement it like this, with both the checkbox and a hidden element:

<input type="checkbox" name="termsAgreement" value="true"> I accept the terms.
<input type="hidden" name="termsAgreement" value="false">

When it is posted back, the HTTP request contains either two values (when checked):

termsAgreement=true&termsAgreement=false

Or one value (when not checked):

termsAgreement=false

It's easy to handle this, as you just have to OR the values either way, and you will get the proper value.

However, if you want to determine the proper value client-side, the only solution I can think of involves some pretty nasty logic.

Is there an elegant way to fairly easily determine the value using JavaScript or jQuery in this case?

Jerad Rose
  • 15,235
  • 18
  • 82
  • 153

1 Answers1

1

I've never bothered with the hidden field. In PHP or Java I would just use the isset (or equivalent) method to see if the value was there and consider it unchecked when it wasn't there.

In your situation I'd look at giving the checkbox itself an id and use the checked property to see if it is checked or not.

HTML:

<input id="termsAgreementCB" type="checkbox" name="termsAgreement" value="true">

Javascript:

var cbRef = getElementById('termsAgreementCB');
if(cbRef.checked) {
   /// The checkbox is checked. 
}

JQuery <= 1.5

if($('#termsAgreementCB").attr('checked')) {
   /// The checkbox is checked.
}

JQuery 1.6

if($('#termsAgreementCB").prop('checked')) {
   /// The checkbox is checked.
}

EDIT Based on your comment I would look into your MVC's documentation and see if it possible to place ids on the outputted inputs. If not you can wrap them in a div.

var $value = ''`enter code here`;
$('#myDiv input').each() {
   if($(this).attr('type') == 'checkbox' && $(this).attr('checked')) {
      $value = $(this).attr('value');
   } else if($(this).attr('type') == hidden && $value == '') {
      $value = $(this).attr('value);
   }
}

If you have more than one checkbox, just abstract this into a method.

Erik Nedwidek
  • 6,134
  • 1
  • 25
  • 25
  • Thanks, but this doesn't solve my problem. I need a solution that works with the combo. This is how [MVC handles checkboxes](http://stackoverflow.com/questions/2697299/asp-net-mvc-why-is-html-checkbox-generating-an-additional-hidden-input), and also seems to be a [common practice in Rails](http://stackoverflow.com/a/2860969/213902). – Jerad Rose Jan 24 '13 at 18:24