Search code examples
javascriptif-statementdisabled-input

If checbox/disable element not working properly


I'm attempting to make a script so that if you check/uncheck a checkbox input, that it will enable/disable a target input text box. My code if statement doesn't seem to function correctly sometimes firing both ifs at once, other times not firing at all. I've done debugging and tried numerous variations but it still won't work. Here is what I have, any help is greatly appreciated!

function disable(elem) {
    var obj = document.getElementById(elem);
    status = obj.disabled;
    console.log(status);
    if (status = true) {
        console.log("test");
        obj.disabled = false;
        obj.style.backgroundColor = "white";
    }
    if (status = false) {
        console.log("test2");
        obj.disabled = true;
        obj.style.backgroundColor = "bfbfbf";
    }
}

Solution

  • This code is not exhibiting proper behavior for several reasons.

    The first reason is that your if statements are inline, not in an if-else form. A better organization is as follows:

    function disable(elem) {
        var obj = document.getElementById(elem);
        status = obj.disabled;
        console.log(status);
        if (status == true) {
            console.log("test");
            obj.disabled = false;
            obj.style.backgroundColor = "white";
        } else {
            console.log("test2");
            obj.disabled = true;
            obj.style.backgroundColor = "#bfbfbf";
        }
    }
    

    This means that even if the variable you are checking changes while the code in the block is executing, it will not execute the code in the opposing block regardless of its new value. As you have it, if the value were to change while the code in the first if statement was running, then it is possible for both control blocks to run.

    The second reason it is not behaving right is due to the incorrect syntax within your if statement. You are currently using the = operator which means set the variable to what you are wanting to check against. You must use either the == or === equality checks (the latter is type strict) if you want to write them this way. An even better way is to omit that operator entirely by just checking if the value is truthy, like so:

    function disable(elem) {
        var obj = document.getElementById(elem);
        status = obj.disabled;
        console.log(status);
        if (status) {
            console.log("test");
            obj.disabled = false;
            obj.style.backgroundColor = "white";
        } else {
            console.log("test2");
            obj.disabled = true;
            obj.style.backgroundColor = "#bfbfbf";
        }
    }
    

    This should give you your expected control behavior :) As was mentioned, make sure you are formatting your values appropriately (e.g. "#bfbfbf" not "bfbfbf")