问题
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?
回答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.
来源:https://stackoverflow.com/questions/36660957/javascript-enabled-input-type-when-checkbox-checked-and-disable-when-checkbox-un