views:

38

answers:

1

Edit I just tried adding this.setAttribute('checked', 'checked'); and it seems to work. Of course just minutes after I make this post....Anyone have any ideas why jQuery's attr() method didn't work?

I can't seem to add a checked attribute to a checkbox via javascript. What I'm trying to do is retain state (via localStorage) of some form elements. For example, say there are 3 checkboxes which each do something. When the user clicks one (either to check or uncheck), I want to save that state in localStorage so when they come back, the form is in the state they left it.

I'm basically just reading and writing an html string with those form elements but I can't seem to get the checked state working.

The code below is a simplified demo. If you run it locally and inspect via Firebug, you'll see that each parent li gets an "on" class (yellow background) and each checkbox gets a custom attribute (foo=true || false) depending on if it's checked or not. So I can set custom attributes but not checked="checked".

Anyone have any ideas?

<!DOCTYPE HTML>

<html>
<head>
<title>checked</title>

<style type="text/css">
li.on {
    background:yellow;
}
</style>

</head>
<body>

<form>
    <ul id="choices">
        <li>
            <input type="checkbox" id="check1" value="checkbox1">
            <label for="check1" class="float">Checkbox 1</label>
        </li>
        <li>
            <input type="checkbox" id="check2" value="checkbox2">
            <label for="check2" class="float">Checkbox 2</label>
        </li>
        <li>
            <input type="checkbox" id="check3" class="float" value="checkbox3">
            <label for="check3" class="float">Checkbox 3</label>
        </li>
    </ul>
</form>


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
<script>
$(function(){

    $('#choices input:checkbox').click(function(){
        var $this = $(this),
            $li = $this.parent();
            module_name =  $this.next().text(),
            module_url = $this.val();

        if (this.checked) { //add checked module
            $li.addClass('on');
            this.checked = true;
            $this.attr('checked', 'checked');
            $this.attr('foo', true);
       } else { //delete unchecked module
            $li.removeClass('on');
            this.checked = false;
            $this.removeAttr('foo');
        }
    });

});
</script>

</body>
</html>
A: 
var checkboxStates = [];

$('input[type=checkbox]').each(function() {

    checkboxStates.push(
        {
            state: this.checked,
                id: this.id
            }
        );

});

If you store that array, then you can iterate back through...

$.each(checkboxStates, function(i, checkboxState) {
     $('#' + checkboxState.id).checked = checkboxState.state;
});
alex