Bobby Pratama
Bobby Pratama

Reputation: 96

Javascript Enabled input type when checkbox checked and disable when checkbox unchecked

my javascript is here:

function enable(id) {
        var i = (document.getElementById('haha').checked);

        if(i= true) {
        document.getElementById("nama_"+id).disabled= false;
        document.getElementById("ket_"+id).disabled= false;
        }else{
            document.getElementById("nama_"+id).disabled= true;
        document.getElementById("ket_"+id).disabled= true;
        }
        }

when i checked checkbox, the textbox will enabled, but when i unchecked, that textbox still enable, i want to this textbox go disabled after i unchecked. how can i fix this problem?

Upvotes: 1

Views: 144

Answers (2)

kuro
kuro

Reputation: 303

function chkBox(obj) {
    console.log(obj);
    $(obj).parents("tr").find("input[type='number']").prop('disabled', !$(obj).is(":checked"));
    $(obj).parents("tr").find("input[type='hidden']").prop('disabled', !$(obj).is(":checked"));
}

call the function and pass this.

onclick="chkBox(this)" 

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075855

= is assignment (setting the value of a variable), so if (i = true) sets i to true and then branches into the if block. To do a comparison, normally you'd use == or ===, but with booleans, that's never necessary; just check the value directly:

if (i) {
    // Enable it
} else {
    // Disable it
}

In this case, though, you can just use i directly:

document.getElementById("nama_"+id).disabled = !i;
document.getElementById("ket_"+id).disabled = !i;

There's also no need for the () around your check of checked.

I'd probably do this:

function enable(id) {
    var disabled = !document.getElementById('haha').checked;
    document.getElementById("nama_"+id).disabled = disabled;
    document.getElementById("ket_"+id).disabled = disabled;
}

There, I'm getting the value of the checkbox and inverting it, then using that as the disabled flag on the other inputs. I'd do it like that because it's nice and easy to debug, I can see the disabled value easily in the debugger when I'm stepping through code.

Some folks really, really like to do things in one expression. (I think that's very overrated.) They might do this:

function enable(id) {
    document.getElementById("nama_"+id).disabled =
        document.getElementById("ket_"+id).disabled =
            !document.getElementById('haha').checked;
}

...since the result of an assignment is the value that was assigned.

Upvotes: 2

Related Questions