簡體   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