2017-02-26 54 views
2

如果用戶開始在input1中輸入一個值,我想禁用input2。如果另一個字段有一個值(動態),使用jquery禁用一個字段

如果input1中沒有值(例如,如果值被刪除),我還希望重新啓用input2。

這是我到目前爲止寫的,但它不工作。

<input id="input1" type="text"> 
<input id="input2" type="text"> 

<script> 
      $(document).ready(function() { 
      if($('#input1').val()) 
      { 
       $('#input2').prop('disabled', true); 
      } 
     }); 
</script> 

回答

2

綁定 「輸入」 和一個 「PropertyChange」 像這樣:

let secondInput = $('#input2'); // Cache the jQuery element 
 
$("#input1").on(
 
    "input propertychange", 
 
    event => secondInput.prop(
 
     'disabled', 
 
     event.currentTarget.value !== "") 
 
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input id="input1" type="text"> 
 
<input id="input2" type="text">

這個工程即使複製/粘貼,拖移,和所有其他的方法。

propertychange是不是必須的,但它是爲IE的支持。

+0

'propertychange'部分是做什麼的? 「輸入」事件不足以涵蓋打字,複製/粘貼等內容?請注意,如果你熱衷於簡潔的代碼,你可以用'secondInput.prop('disabled',event.currentTarget.value!=「」);' – nnnnnn

+0

替換if/else,我。謝謝! – kevinkt

+0

@nnnnnn接受了關於一班輪的建議。 propertychange是IE垃圾。有所有的瀏覽器,還有IE瀏覽器。我討厭IE。 – Bharel

0

如果你不想在第一個輸入被改變的時候禁用第二個輸入,你可以監聽輸入並將其禁用改爲true。在這個例子中,我只在第一個輸入不是空的時候這樣做。

<input id="input1" type="text"> 
<input id="input2" type="text"> 

<script> 
    $(document).ready(function() { 
     $('#input1').on('keyup', function(e){ 
      if(e.target.value.length > 0){ 
       $('#input2').prop('disabled', true); 
      }else{ 
       $('#input2').prop('disabled', false); 
      } 
     }); 
    }); 

</script> 
+0

如果用戶在不使用鍵盤的情況下更改值,該怎麼辦? – nnnnnn

相關問題