如何使用Javascript禁用输入字段?

Jor*_*eFG 16 html javascript disabled-input

我从Javascript开始,我写了这个函数:

function disableField() {
  if( document.getElementById("valorFinal").length > 0 ) ) {
    document.getElementById("cantidadCopias").disabled = true; 
  }
}
Run Code Online (Sandbox Code Playgroud)

如果填充第一个字段,则禁用名为cantidadCopias的第二个字段.

<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>
Run Code Online (Sandbox Code Playgroud)

但是当第一个字段填满时,它不会禁用第二个字段.

epa*_*llo 22

你看看控制台了吗?

  • 未捕获的SyntaxError:意外的令牌)
  • 未捕获的ReferenceError:未定义disableField

第一次出现拼写错误时,现在您的代码有额外的错误 )

function disableField() {
  if( document.getElementById("valorFinal").length > 0 ) ) {  <-- extra )
    document.getElementById("cantidadCopias").disabled = true; 
  }
}?
Run Code Online (Sandbox Code Playgroud)

现在下一个问题是你没有看到价值的长度.

if( document.getElementById("valorFinal").length > 0 )  <-- you are looking at the length of the HTML DOM Node.
Run Code Online (Sandbox Code Playgroud)

所以代码应该是这样的

function disableField() {
  if( document.getElementById("valorFinal").value.length > 0 ) { 
    document.getElementById("cantidadCopias").disabled = true; 
  }
}?
Run Code Online (Sandbox Code Playgroud)

但现在如何编写它,一旦被禁用,它将不会被重新启用.

function disableField() {
    var isDisabled = document.getElementById("valorFinal").value.length > 0; 
    document.getElementById("cantidadCopias").disabled = isDisabled;
}?
Run Code Online (Sandbox Code Playgroud)