2013-07-11 10 views
13

Zobacz tutaj: http://jsfiddle.net/nShQs/Jak włączyć dynamicznie wyłączone pole wyboru?

Naciśnij przycisk wyłączania, a następnie przycisk włączania. Pole wyboru nie zostanie włączone.

HTML:

<input id="check" type="checkbox"/> 
<input id="btn1" type="button" value="enable" /> 
<input id="btn2" type="button" value="disable" /> 

JS:

function enable() { 
    var x = document.getElementById("check"); 
    alert(x.getAttribute("disabled")); 
    x.setAttribute("disabled", "false"); 
    alert(x.getAttribute("disabled")); 
} 

function disable() { 
    var x = document.getElementById("check"); 
    alert(x.getAttribute("disabled")); 
    x.setAttribute("disabled", "true"); 
    alert(x.getAttribute("disabled")); 
} 
document.getElementById("btn1").addEventListener("click", enable); 
document.getElementById("btn2").addEventListener("click", disable); 

odpowiedź

W odpowiedzi powiedzieć to dlatego, że atrybut jest atrybutem disabled logiczna. Zobacz here.

+1

wybrałem odpowiedź PSL, bo odpowiedział 1st. – batman

Odpowiedz

21

Wystarczy zrobić

function enable() { 
    document.getElementById("check").disabled= false; 

} 

function disable() { 
    document.getElementById("check").disabled= true; 
} 

Mając to ustawiasz właściwość elementu DOM, podczas ustawiania obecność atrybutu atrybutu disabled wyłączy pole wyboru, więc nawet jeśli nie x.setAttribute("disabled", "false"); to nadal będzie tam element jako atrybut.

Demo

czy też po prostu zrobić:

function disable() { 
    document.getElementById("check").setAttribute('disabled', 'disabled'); 
} 

function enable() { 
    document.getElementById("check").removeAttribute('disabled'); 
} 

disabled jako atrybutu i disabled jako nieruchomości są różne.

+0

Czym różni się to od tego, co zrobiłem? – batman

+0

@learner użyłeś go jako functoin, to nie jest jeden –

+0

@learner zobaczyć odpowiedź, dałem wyjaśnienie. – PSL

6

Ustaw właściwośćdisabledzamiast atrybut (fiddle) .

function enable() { 
    document.getElementById("check").disabled = false;  
} 

function disable() { 
    document.getElementById("check").disabled = true; 
} 

Kontrola pozostanie wyłączona, jeśli disabledatrybut występuje wcale - niezależnie od jego wartości (fiddle). Ustawienie atrybutu do do spowoduje usunięcie atrybutu .

Powiązane problemy