I would like to know how do I combine the below two checkboxes to know both have been checked and I want to write their values in a hidden field.
These are my checkboxes and a hidden field:
<input type="checkbox" name="chkText" id="cbA" value="" />A
<input type="checkbox" name="chkText" id="cbB" value="B" />B
<input id="TextSelection" type="hidden" />
I want to know something can be written like this as this is not working
if ($('#cbA','#cbB').is('checked')) {
$('#TextSelection').val("A and B");
}
Just write in the longer form:
Simplified, working, JS Fiddle demo.
Originally-posted, non-working, jQuery:
The reason that your code, as posted, wasn’t working is the order of the
if/else ifstatements.If both checkboxes are checked the this meets the requirement of the first of the
ifassessments; JavaScript doesn’t assess whether there’s anotherifthat could be more true, it simply executes what it finds following the first assessment which returnstrue.To keep the structure in that order you could add
&& $(otherCheckbox).not(':checked'), but that’s overly verbose. All you have to do is move the most-difficult-to-satisfy assessment ahead of the others that can be matched under multiple scenarios.