Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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("cantidadCopias").disabled = true; 
  }
}

Which disables the second field named cantidadCopias if the first one is filled.

<label> <span>Valor final:</span>
  <input type="text" class="input_text" name="valorFinal" id="valorFinal" onkeydown="disableField()"/>
</label>
<label> <span>Cantidad de Copias:</span>
  <input type="text" class="input_text" name="cantidadCopias" id="cantidadCopias"/>
</label>

But it's not disabling the second field when the first one is filled.

like image 413
JorgeeFG Avatar asked Oct 15 '12 13:10

JorgeeFG


People also ask

How do I disable input field typing?

The disabled attribute is a boolean attribute. When present, it specifies that the <input> element should be disabled. A disabled input element is unusable and un-clickable.

How do you disable something in JavaScript?

To disable a button using only JavaScript you need to set its disabled property to false . For example: element. disabled = true . And to enable a button we would do the opposite by setting the disabled JavaScript property to false .

How do I disable input field numbers?

If you are able/allowed to use jQuery, you can disable keypress on the type='number' . $("[type='number']"). keypress(function (evt) { evt. preventDefault(); });

How do I disable input field editing?

You can either use the readonly or the disabled attribute. Note that when disabled, the input's value will not be submitted when submitting the form. Also It's important to remind that even using readonly attribute, you should never trust user input which includes form submissions.


1 Answers

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 )

function disableField() {
  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

function disableField() {
  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.

function disableField() {
    var isDisabled = document.getElementById("valorFinal").value.length > 0; 
    document.getElementById("cantidadCopias").disabled = isDisabled;
}​
like image 109
epascarello Avatar answered Sep 22 '22 19:09

epascarello