synergetic
synergetic

Reputation: 8026

cannot check/uncheck checkbox in javascript/jquery

I have a checkbox which will toggle some other check boxes on a html form:

<input type="checkbox" name="selector" onclick="toggle_all(this);"/>

<script language="javascript">
function toggle_all(source) {
    var checkboxes = $(":input[name^='form[r']");
    if($(source).is(':checked')) {
        checkboxes.attr('checked', 'checked');
    } else {
        checkboxes.removeAttr('checked');
    }
    alert('done');
}
</script>

First time I click the "selector" check box, all check boxes with names starting "form[r" will be checked. Then when "selector" check box is unchecked, all others are unchecked as well. Since then checking/unchecking "selector" checkbox doesn't affect other checkboxes. The code is running because alert('done') shows up. What's wrong here?

Upvotes: 2

Views: 3368

Answers (3)

dfsq
dfsq

Reputation: 193251

I would suggest an improvement. Change HTML, add some class to all your checkboxes:

<input class="check" type="checkbox" name="form[r]">

And JS:

function toggle_all(source) {
    $(".check").prop('checked', source.checked);
}

http://jsfiddle.net/tFv3G/

And the reason why is that searching elements by its attributes much slower than by class name. And less readable as well.

Upvotes: 2

dimusic
dimusic

Reputation: 4133

I'd recomment using this code to select/deselect all checkboxes:

$('input#select-all').change(function(){
  var checked = $(this).prop('checked');
  $(":input[name^='form[r']").prop('checked', checked);
});

Upvotes: 0

Adil
Adil

Reputation: 148110

You need to escape the square bracket in selector

Change

var checkboxes = $(":input[name^='form[r']");

To

var checkboxes = $(":input[name^='form\[r']");

Upvotes: 1

Related Questions