2

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?

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to escape the square bracket in selector

Change

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

To

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

2 Comments

You need to double escape it using \\: Check this fiddle: jsfiddle.net/NAwhN
I don't know why, but it works both way, whether escaped or not.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.