I see lots of people on stackoverflow, across the internet, and my colleagues use values in their checkboxes that are not 1 or 0 (ex. <input type='checkbox' value='check'/>
), but my thought is that essentially a checkbox will always be a yes/no answer.
Currently I use a jQuery script I wrote to standardize across my applications that looks like:
;(function($){
$(document).ready(function() {
var selector = 'input[type="checkbox"]';
var c = 'checked';
$.each($(selector),function(){
var $el,value,attr;
$el = $(this);
value = $el.val();
attr = $el.attr(c);
if(value == 1 || typeof(attr) !== 'undefined')
{
$el.attr(c,c);
$el.prop(c,true);
$el.val(1);
}
else{
$el.removeAttr(c);
$el.prop(c,false);
$el.val(0);
}
});
$(selector).change(function(e){
var $el, checked = null;
$el = $(this);
checked = $el.prop(c);
if (checked) {
$el.attr(c,c);
$el.val(1);
} else {
$el.removeAttr(c);
$el.val(0);
}
});
});
})(jQuery);
So that I can handle any of these situations:
<input type='checkbox' value='1'/>
<input type='checkbox' checked/>
<input type='checkbox' checked='checked'/>
<input type='checkbox' value='1' disabled/>
<input type='checkbox' checked disabled/>
<input type='checkbox' checked='checked' disabled/>
<input type='checkbox' value='0'/>
<input type='checkbox'/>
<input type='checkbox' value='0' disabled/>
<input type='checkbox' disabled/>
But it does not account for any values of the checkboxes that are not 0 or 1 or having the attribute 'checked'.
My question is: Is there ever a good use-case for using a non 0/null or 1 value (especially when working with a relational database)?
Consider the following: "chose your favorite fruits (check all that apply)".
your method:
<input type="checkbox" name="choice_apple" value="1" />
<input type="checkbox" name="choice_orange" value="1" />
<input type="checkbox" name="choice_durian" value="1" />
or you could use something like:
<input type="checkbox" name="choice[]" value="apple" />
<input type="checkbox" name="choice[]" value="orange" />
<input type="checkbox" name="choice[]" value="durian" />
the back-end storage system is irrelevant to this. we're just talking about checkboxes. your method requires 3 separate form field names, with the "value" of the choice embedded in the name. Extra overhead is required to extract that name so you can actually store the fruit's name somewhere.
Whereas, with the "useful value" version, it's one single form field. PHP will convert the choices to an array - and you end up with the exact name you need, without extra any extraction/processing required.
Remember: checkboxes which aren't selected are NOT submitted with a normal form submission. There's an implicit true/false right there already. If you get a checkbox's field name at the server, the checkbox WAS selected.
Since you already have a nicely built-in true/false, why not layer on the extra semantics of saying what the true/false represents?