[英]How to disable the remaining input field depend upon the value entered in the textfield?
我有三個輸入字段,並且所有字段都已啟用。 現在,當用戶在任何字段中輸入文本時,其余字段應禁用。
例如,用戶在名稱字段中輸入emp_id
和temp_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.