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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but this doesn't solve my problem. I need a solution that works with the combo. This is how MVC handles checkboxes, and also seems to be a common practice in Rails.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.