我有三个输入字段,并且所有字段均已启用。现在,当用户在任何字段中输入文本时,该字段的其余部分应该禁用。
例如,用户在名称字段中输入 emp_id
和 temp_id
字段已禁用
,或者如果输入 emp_id
code> 字段,然后禁用名称和 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">
关于javascript - 如何根据文本字段中输入的值禁用剩余的输入字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51112437/