jQuery - 禁用表单字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1387341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:19:56  来源:igfitidea点击:

jQuery - Disable Form Fields

jqueryforms

提问by user159025

I have 2 fields: 1 input, 1 select box.

我有 2 个字段:1 个输入,1 个选择框。

Is it possible to make the browser disable one of the fields when the user uses the other?

当用户使用另一个字段时,是否可以让浏览器禁用其中一个字段?

For example, if the user is entering data into the input, the select box is disabled. If the user is selecting data from the select (dropdown), the input is disabled.

例如,如果用户在输入中输入数据,则选择框将被禁用。如果用户从选择(下拉)中选择数据,则输入被禁用。

Any help with this would be much appreciated.

对此的任何帮助将不胜感激。

Cheers in advance.

提前加油。

回答by Matt Howell

<script type="text/javascript" src="jquery.js"></script>          
<script type="text/javascript">
  $(document).ready(function() {
      $("#suburb").blur(function() {
          if ($(this).val() != '')
              $("#post_code").attr("disabled", "disabled");
          else
              $("#post_code").removeAttr("disabled");
      });

      $("#post_code").blur(function() {
          if ($(this).val() != '')
              $("#suburb").attr("disabled", "disabled");
          else
              $("#suburb").removeAttr("disabled");
      });
  });
</script>

You'll also need to add a value attribute to the first option under your select element:

您还需要在 select 元素下的第一个选项中添加一个 value 属性:

<option value=""></option>

回答by MetaSkills

The jQuery docs say to use prop() for things like disabled, checked, etc. Also the more concise way is to use their selectors engine. So to disable all form elements in a div or form parent.

jQuery 文档说使用 prop() 来处理禁用、检查等。另外更简洁的方法是使用他们的选择器引擎。因此要禁用 div 或表单父级中的所有表单元素。

$myForm.find(':input:not(:disabled)').prop('disabled',true);

And to enable again you could do

并再次启用你可以做

$myForm.find(':input:disabled').prop('disabled',false);

回答by Rigobert Song

$('input, select').attr('disabled', 'disabled');

回答by Nrj

try this

尝试这个

$("#inp").focus(function(){$("#sel").attr('disabled','true');});

$("#inp").blur(function(){$("#sel").removeAttr('disabled');});

vice versa for the select also.

反之亦然。

回答by Rohit bal

Here's a jquery plugin to do the same: http://s.technabled.com/jquery-foggle

这是一个 jquery 插件来做同样的事情:http: //s.technabled.com/jquery-foggle