Reputation: 542
HTML
<label for="desktop_dimension_id">Desktop dimensions:</label>
<span class="checkbox" id="desktopCheckboxId">
<span class="checkbox_value">
<input id="dc1280_800" type="checkbox" name="1280x800"> 1280x800</span>
<span class="checkbox_value">
<input id="dc1366_768" type="checkbox" name="1366x768"> 1366x768</span>
<span class="checkbox_value">
<input id="dc1920_1080" type="checkbox" name="1920x1080"> 1920x1080</span>
</span>
<br/>
<input id="desktopCheckbox" type="checkbox" name="type[]" value="1"> Desktop
JAVASCRIPT
if(jQuery('#desktopCheckboxId input[type=checkbox]:checked').length) {
document.getElementById('desktopCheckbox').checked = this.checked;
}
I want to check the desktop checkbox is any of the first three checkboxes is checked. Have been trying several methods but doesn't seem to work for unknown reasons. So how will I be able to do that?
Upvotes: 1
Views: 230
Reputation: 326
Try this one.
$("#frmTest input[type='checkbox']").each(function(){
if($(this).is(':checked'))
{
$("#desktopCheckbox").attr("checked","checked");
return true;
}
});
Upvotes: 3
Reputation: 4146
you can just set checked = true...
if (jQuery('input[type=checkbox]:checked').length) {
document.getElementById('desktopCheckbox').checked = true;
}
(btw, your fiddle was also looking for a form id that didn't exist... "frmTest")
Upvotes: 1
Reputation: 57105
var chk = $('.checkbox_value input[type=checkbox]');
chk.change(function () {
$('#desktopCheckbox').prop('checked', chk.filter(':checked').length > 0);
});
Upvotes: 1
Reputation: 34117
how about this: Demo http://jsfiddle.net/GGEFp/ *<== will return false
http://jsfiddle.net/D23eA/ <== will return true
API: length
http://api.jquery.com/length/
Rest should fit the need :)
Code
var atLeastOne = $('#desktopCheckboxId :checkbox:checked').length > 0;
Upvotes: 2
Reputation: 160943
You could just do like below:
$('#desktopCheckbox').prop('checked', $('#frmTest input[type=checkbox]:checked').length > 0);
But you may mean to bind with change event.
$('#frmTest input[type=checkbox]').change(function() {
$('#desktopCheckbox').prop('checked', $('#frmTest input[type=checkbox]:checked').length > 0);
}).change();
Upvotes: 2