繁体   English   中英

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

[英]How to disable an input field using Javascript?

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

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

如果填充第一个字段,则禁用名为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>

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

你看看控制台了吗?

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

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

function disableField() {
  if( document.getElementById("valorFinal").length > 0 ) ) {  <-- extra )
    document.getElementById("cantidadCopias").disabled = true; 
  }
}​

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

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

所以代码应该是这样的

function disableField() {
  if( document.getElementById("valorFinal").value.length > 0 ) { 
    document.getElementById("cantidadCopias").disabled = true; 
  }
}​

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

function disableField() {
    var isDisabled = document.getElementById("valorFinal").value.length > 0; 
    document.getElementById("cantidadCopias").disabled = isDisabled;
}​

最好使用onkeyup()而不是onkeydown() 问题是在keydown事件上没有更新输入的值。

小提琴

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

JavaScript的

function disableField(val) {
    var cantidadCopias = document.getElementById("cantidadCopias");
    cantidadCopias.disabled = ( val.length > 0  );
}

javascript:

var disableField = function () {
  var state = document.getElementById("valorFinal").value.length > 0;
  document.getElementById("cantidadCopias").disabled = state;
}​;​

html:

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

当输入长度再次为0时,您也应该再次启用它。

除此之外,你应该挂钩onkeyup而不是onkeydown。

你可以在这里试试: jsfiddle.net/DBJfN/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM