Tom Harger
Tom Harger

Reputation: 1

Setting and unsetting an attribute works only once

I have a form with several checkboxes that I'm trying to check/uncheck by clicking certain links. It works the first time I use it, but then fails every time there after. Code is:

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Checkbox Test</title>
<script type="text/javascript" src="/js/jquery.js"></script>
<script language="javascript">
    $('document').ready(function() {
        $('#chkAll').click(function() {
            $('input[type="checkbox"]').attr('checked', 'checked');
        });
        $('#unChkAll').click(function() {
            $('input[type="checkbox"]').removeAttr('checked');
        });
    });
</script>
<style type="text/css"> 
span {
    text-decoration: underline;
    cursor: pointer;
}
</style>
</head>

<body>
<h2>Checkbox Test</h2>
<form name="form1" method="post" action="">
    <p>
        <label>
            <input type="checkbox" name="CheckboxGroup1" value="checkbox" id="CheckboxGroup1_0">
            Checkbox</label>
        <br>
        <label>
            <input type="checkbox" name="CheckboxGroup1" value="checkbox" id="CheckboxGroup1_1">
            Checkbox</label>
        <br>
    </p>
</form>
<p><span id="chkAll">Check All</span> / <span id="unChkAll">Uncheck all</span></p>
</body>
</html>

I'm not sure what going on here. When I inspect the input element using firebug, it shows the "Checked" attribute being set and unset. Yet, when actually looking at the checkboxes, nothing changes.

Help is required.

Upvotes: 0

Views: 84

Answers (3)

Kiran
Kiran

Reputation: 20303

Use .prop() instead of .removeAttr() which removes an attribute from element:

$('document').ready(function() {
        $('#chkAll').click(function() {
            $('input[type="checkbox"]').prop('checked', true);
        });
        $('#unChkAll').click(function() {
            $('input[type="checkbox"]').prop('checked', false);
        });
    });

DEMO

Upvotes: 1

Amit Joki
Amit Joki

Reputation: 59282

use .prop

$('document').ready(function() {
        $('#chkAll').click(function() {
            $('input[type="checkbox"]').prop('checked', true);
        });
        $('#unChkAll').click(function() {
            $('input[type="checkbox"]').prop('checked',false);
        });
    });

Learn more about it here

Upvotes: 1

Felix
Felix

Reputation: 38112

Your code is not working after first time as you've described is because you're using .removeAttr() so it'll permanently remove your checked attribute from all the checkboxes.

So, in your case you want to set it instead of removing it, that's why you should use .prop() instead of .removeAttr():

$('document').ready(function () {
    $('#chkAll').click(function () {
        $('input[type="checkbox"]').prop('checked', true);
    });
    $('#unChkAll').click(function () {
        $('input[type="checkbox"]').prop('checked', false);
    });
});

Fiddle Demo

Upvotes: 1

Related Questions