Cat
Cat

Reputation: 37

Store multiple checkbox state with jquery.cookie.js

I want to store a checkbox state in cookie with this :

<script type="text/javascript">
$(document).ready(function(){
var checkbox = $('#boxlawreg :checkbox'),
    checkboxCookieName = 'checkbox-state';

checkbox.prop('checked', +$.cookie(checkboxCookieName));

checkbox.click(function() {
   $.cookie(checkboxCookieName, +this.checked);
});
});
</script>

It's work great but i have 7 checkbox and if i check one, reload my website, all the checkbox are check.

it's look like :

<input type="checkbox" name="option1" value="1">
<input type="checkbox" name="option2" value="2">
<input type="checkbox" name="option3" value="3">
<input type="checkbox" name="option4" value="4">

Any ideas ?

(Ps: Sorry for the english, i'm french)

Upvotes: 0

Views: 3837

Answers (1)

Thulasiram
Thulasiram

Reputation: 8552

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script src="https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js"
        type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var checkbox = $('#boxlawreg').find(':checkbox'), checkboxCookieName = 'checkbox-state';

            checkbox.each(function () {
                $(this).attr('checked', $.cookie(checkboxCookieName + '|' + $(this).attr('name')));
            });

            checkbox.click(function () {
                $.cookie(checkboxCookieName + '|' + $(this).attr('name'), $(this).prop('checked'));
            });
        });
    </script>
</head>
<body>
    <div id="boxlawreg">
        <input type="checkbox" name="option1" value="1" />1<br />
        <input type="checkbox" name="option2" value="2" />2<br />
        <input type="checkbox" name="option3" value="3" />3<br />
        <input type="checkbox" name="option4" value="4" />4<br />
    </div>
</body>
</html>

Upvotes: 3

Related Questions