Skip to content Skip to sidebar Skip to footer

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=

Solution 1:

= 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.


Post a Comment for "Javascript Enabled Input Type When Checkbox Checked And Disable When Checkbox Unchecked"