mickzer
mickzer

Reputation: 6358

JQUERY - If statement inside function won't work

I have a function that listens for the change of a checkbox. When the page loads, the checkbox will be either ticked or unticked depending on previously completed steps.

I want to record if the checkbox is changed or not. And if it is changed, and then changed again, it will have been reset to the value it started with, therefore meaning there is no change in it's value.

I wrote the following code to do this.

//Checkboxes
    var change ="<input class=\"changed\" type=\"hidden\" name=\"changed\" value=\"1\"/>";
    var nochange ="<input class=\"changed\" type=\"hidden\" name=\"changed\" value=\"0\"/>";
    var changed=false;
    $(".change-event").change(function(){
        //alert("checked");

        if(changed==false) {
            $(this).next(".changed").remove();
            $(this).after(change);
            changed=true;
        }   

        if(changed==true) {

            $(this).next(".changed").remove();
            $(this).after(nochange);
            changed=false;

        }

    });

The if statements inside the change function aren't working. The change function itself has no issues as the commented out alert works fine.

I have tried if(!checked) and also if(checked) as the conditions too, but it still didn't work.

Help appreciated.

Upvotes: 0

Views: 674

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388446

you need

    if(changed==false) {
        $(this).next(".changed").remove();
        $(this).after(change);
        changed=true;
    } else {

        $(this).next(".changed").remove();
        $(this).after(nochange);
        changed=false;

    }

else at start value of changed is false then the first if condition is satisfied... it changes the value of changed to true. Then the second condition is checked again it will be satisfied because the value of changed is already changed by the first if thus the second block also will get called... thus it negates all the changes done by the first block.


But it looks like it can be simplified to

var change = "<input class=\"changed\" type=\"hidden\" name=\"changed\" value=\"1\"/>";
var nochange = "<input class=\"changed\" type=\"hidden\" name=\"changed\" value=\"0\"/>";
var changed = false;
$(".change-event").change(function () {
    $(this).next(".changed").remove();
    $(this).after(changed ? nochange : change);
    changed = !changed;
});

Upvotes: 4

Related Questions