2017-02-26 56 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

相关问题