javascript - 如何根据文本字段中输入的值禁用剩余的输入字段?

标签 javascript jquery html

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

例如,用户在名称字段中输入 emp_idtemp_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/

相关文章:

javascript - 在 Jasmine 中模拟假按键

php - 在图像上标记点

html - 如何使flex从底部显示元素

javascript - 无法从主体 onload 调用函数(未捕获的引用错误 : resetLoginForm is not defined) javascript

javascript - Angular 4 的平均堆栈应用程序

javascript - 在 javascript 中 bool 比较与精确匹配搜索之间进行搜索的更快方法

javascript - 如何在从 html 集合创建的数组中通过 for 循环从对象中获取元素的值?

Javascript:让 JS 处理大量动态添加的 HTML 内容的最佳方法。委托(delegate)/重新触发/或其他?

php - 有些东西让我的页面多次执行 Ajax 调用... [读取 : I've never been more frustrated with something so 'simple' in my life]

javascript - Angular2 : JQuery $. 为 Angular2/4 扩展