How To Disable An Input Field Using Javascript?
I'm starting with Javascript, I wrote this function: function disableField() { if( document.getElementById('valorFinal').length > 0 ) ) { document.getElementById('cantidad
Solution 1:
Did you look at the console?
- Uncaught SyntaxError: Unexpected token )
- Uncaught ReferenceError: disableField is not defined
First time you had a spelling error, now your code has an extra )
functiondisableField() {
if( document.getElementById("valorFinal").length > 0 ) ) { <-- extra )
document.getElementById("cantidadCopias").disabled = true;
}
}
Now the next issue is you are not looking at the length of the value.
if( document.getElementById("valorFinal").length >0 ) <-- you are looking at the length of the HTML DOM Node.
So the code should look like
functiondisableField() {
if( document.getElementById("valorFinal").value.length > 0 ) {
document.getElementById("cantidadCopias").disabled = true;
}
}
but now how it is written, once it is disabled, it will not be re-enabled.
functiondisableField() {
var isDisabled = document.getElementById("valorFinal").value.length > 0;
document.getElementById("cantidadCopias").disabled = isDisabled;
}
Solution 2:
It is best if you use onkeyup()
instead of onkeydown()
. The problem is the value of the input is not updated on keydown event.
<label><span>Valor final:</span><inputtype="text"class="input_text"name="valorFinal"id="valorFinal"onkeyup="disableField(this.value)"/></label><label><span>Cantidad de Copias:</span><inputtype="text"class="input_text"name="cantidadCopias"id="cantidadCopias"/></label>
javascript
functiondisableField(val) {
var cantidadCopias = document.getElementById("cantidadCopias");
cantidadCopias.disabled = ( val.length > 0 );
}
Solution 3:
the javascript:
var disableField = function () {
var state = document.getElementById("valorFinal").value.length > 0;
document.getElementById("cantidadCopias").disabled = state;
};
the html:
<label><span>Valor final:</span><inputtype="text"class="input_text"name="valorFinal"id="valorFinal"onkeyup="disableField()"/></label><label><span>Cantidad de Copias:</span><inputtype="text"class="input_text"name="cantidadCopias"id="cantidadCopias"/></label>
you should also enable it again when the input length is 0 again.
besides that you should hook onkeyup and not onkeydown.
you can try it here: jsfiddle.net/DBJfN/
Post a Comment for "How To Disable An Input Field Using Javascript?"