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?

4
  • Does your condition pass already when you console.log inside ? Commented Sep 28, 2018 at 7:57
  • yes, i edited the jsfiddle for that, but it passes only the first time, when i check/uncheck the checkbox nothing happens Commented Sep 28, 2018 at 8:00
  • Possible duplicate of jQuery checkbox change and click event Commented Sep 28, 2018 at 8:09
  • @DevHugo i don't think it's the same question. i'am using jquery cookie plugin Commented Sep 28, 2018 at 8:15

2 Answers 2

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});
        }
}
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your comment, in fact, i will use a on change property. i'll post the answer.
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}); 
    }
});

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.