I try to set up a checkbox with a label which works both on click and also can be controlled via Javascript. The idea is that the user can on first visit to the site click the label which activates the checkbox and places a cookie. Upon return to the site, the checkbox should already checked if the cookie is placed. This all works fine with the checkbox itself but the label will always be unchecked upon return to the page.
My code (I am excluding the script that places/retrieves the cookie, that is working fine):
var class1cookie = getCookie('class1c');
$(document).ready(function() {
if (class1cookie == "yes") {
document.getElementById('class1').checked = true;
}
$('#class1label').click(function() {
if (document.getElementById('class1').checked == false) {
x1 = "yes";
count = count + 1;
setCookie('class1c', "yes", '1');
} else if (document.getElementById('class1').checked == true) {
x1 = "no";
count = count - 1;
setCookie('class1c', "no", '1');
}
<label id="class1label">Class 1<input type="checkbox" id="class1"></label>
One other thing I am confused about: My .click function seems to only work if properly if the true/false conditions in the following part are reversed -> it seems that by clicking the label, the checkbox does not update straight away. When I remove the label and attach the .click function directly to the ckeckbox, the true/false conditions for the checkbox work correctly.
Many thanks!!
Aucun commentaire:
Enregistrer un commentaire