1

I have a form and a cookie that have to be of the same value of a checkbox input field, i want the cookie to change its value (true/false) when i check/uncheck the checkbox.

Here is what i tried but it doesn't seem to work :

<input id="checkbox1" type="checkbox" name="performance" value="checked" checked="checked"> checkbox number 1
if ($('input#checkbox1').is(':checked')) {
  $.cookie('cookie1', 'true', { expires: 60});
} else {
  $.removeCookie("cookie1");
  $.cookie('cookie1', 'false', { expires: 60});
}

A jsFiddle: https://jsfiddle.net/kdfhb4n9/6/

I don't know what am I doing wrong, can you help?

Dhon Joe
  • 212
  • 1
  • 11
  • Does your condition pass already when you console.log inside ? – Dinosan0908 Sep 28 '18 at 07:57
  • yes, i edited the jsfiddle for that, but it passes only the first time, when i check/uncheck the checkbox nothing happens – Dhon Joe Sep 28 '18 at 08:00
  • Possible duplicate of [jQuery checkbox change and click event](https://stackoverflow.com/questions/7031226/jquery-checkbox-change-and-click-event) – DevHugo Sep 28 '18 at 08:09
  • @DevHugo i don't think it's the same question. i'am using jquery cookie plugin – Dhon Joe Sep 28 '18 at 08:15

2 Answers2

4

add an event to you code, like on click or on change because currently its only runs onload.

function check(){
    if ($('input#checkbox1').is(':checked')) {
        console.log("true inside");
             $.cookie('cookie1', 'true', { expires: 60} );
            }
            else
            {
            console.log("false");
                $.removeCookie("cookie1");
                $.cookie('cookie1', 'false', { expires: 60});
        }
}
});
Harsh Metrey
  • 133
  • 5
2

so thanks to @harsh-metrey, i found the answer, i was in fact running the script on load:

$("input#checkbox1").change(function() {
    if($(this).is(":checked")) { 
        $.cookie("cookie1", "true", {expires: 60}); 
    }
    else { 
        $.cookie("cookie1", "false", {expires: 60}); 
    }
});
Community
  • 1
  • 1
Dhon Joe
  • 212
  • 1
  • 11