vephelp
vephelp

Reputation: 542

Check checkbox if any of the checkboxes is checked

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?

jsFiddle

Upvotes: 1

Views: 230

Answers (5)

Ramz
Ramz

Reputation: 326

http://jsfiddle.net/pmZ7T/

Try this one.

$("#frmTest input[type='checkbox']").each(function(){
    if($(this).is(':checked'))
    {
        $("#desktopCheckbox").attr("checked","checked");
        return true;
    }
});

Upvotes: 3

Jeff
Jeff

Reputation: 4146

you can just set checked = true...

if (jQuery('input[type=checkbox]:checked').length) {
        document.getElementById('desktopCheckbox').checked = true;
    }

http://jsfiddle.net/pmZ7T/4/

(btw, your fiddle was also looking for a form id that didn't exist... "frmTest")

Upvotes: 1

fiddle Demo

var chk = $('.checkbox_value input[type=checkbox]');
chk.change(function () {
    $('#desktopCheckbox').prop('checked', chk.filter(':checked').length > 0);
});


References

.change()

.prop()

.filter()

Upvotes: 1

Tats_innit
Tats_innit

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

xdazz
xdazz

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();

See the demo.

Upvotes: 2

Related Questions