繁体   English   中英

如何禁用剩余的输入字段,具体取决于在文本字段中输入的值?

[英]How to disable the remaining input field depend upon the value entered in the textfield?

我有三个输入字段,并且所有字段都已启用。 现在,当用户在任何字段中输入文本时,其余字段应禁用。

例如,用户在名称字段中输入emp_idtemp_id字段被disabled或者如果在emp_id字段中输入则禁用name和temp_id,或者如果输入temp_id则禁用名称和emp_id文本字段。

我对在if-else条件中使用逻辑感到困惑。 您能帮我这个忙吗?

 $(document).ready(function(){ $('.disabled_field').on('keyup',function(){ if($(this).val().length >0){ // $("").prop('disabled','disabled'); }else{ // $("").removeProp('disabled','disabled'); } }); }); 
 <input type="text" name="name" class="disable_field" placeholder="name"> <input type="text" name="emp_id" class="disable_field" placeholder="emp_id"> <input type="text" name="temp_id" class="disable_field" placeholder="temp_id"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

我认为input事件更适合这种情况。 根据控件的值的长度更改属性。 只需使用not :not()选择器即可禁用所有输入。 请尝试以下操作:

 $(document).ready(function(){ $('.disable_field').on('input',function(){ if($(this).val().length) // Checks if there is any value present or not $('.disable_field').not(this).prop('disabled', true); // Disable all input except the current. else $('.disable_field').removeAttr('disabled'); // Enable all input by removing the "disabled" property from controls. }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" name="name" class="disable_field" placeholder="name"> <input type="text" name="emp_id" class="disable_field" placeholder="emp_id"> <input type="text" name="temp_id" class="disable_field" placeholder="temp_id"> 

尝试这个。

 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <input type="text" name="name" class="disable_field" placeholder="name"> <input type="text" name="emp_id" class="disable_field" placeholder="emp_id"> <input type="text" name="temp_id" class="disable_field" placeholder="temp_id"> <script> $(document).ready(function(){ $('input.disable_field').keyup(function(){ if ($(this).val().length === 0) { $('input.disable_field').prop('disabled', false); } else { $('input.disable_field').prop('disabled', true); $(this).prop('disabled', false); } }); }); </script> </body> </html> 

干得好:

 $(document).ready(function() { var inputs = $('.disable_field'); inputs.on('keyup', function() { if (this.value.length > 0) { inputs.filter((i, f) => f !== this).prop('disabled', true); } else { inputs.prop('disabled', false); } }); }); 
  <input type="text" name="name" class="disable_field" placeholder="name"> <input type="text" name="emp_id" class="disable_field" placeholder="emp_id"> <input type="text" name="temp_id" class="disable_field" placeholder="temp_id"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

暂无
暂无

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

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