javascript 根据下拉菜单中的选择显示/隐藏表单字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26252272/
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-10-28 05:43:15  来源:igfitidea点击:

Show/hide form fields based on a selection from a drop down menu

javascriptjqueryhtml

提问by Plastik

I have this code but problem is that when the value is blank (option 1) states are shown up. How to hide it if the value is blank?

我有这个代码,但问题是当值为空时(选项 1)状态会显示出来。如果值为空,如何隐藏它?

<select id="country"">
    <option value="" disabled="disabled" selected="selected">PLEASE CHOOSE</option>
    <option value="USA">USA</option>
    <option value="UK">UK</option>
    <option value="IT">ITALY</option>
</select>
<div id="states">
</div>

    $(document).ready(function(){
    $('#country').on('change', function() {
      if ( this.value == 'USA')
      {
        $("#states").show();
      }     
        else
      {
        $("#states").hide();
     }
    });
});

回答by Arun P Johny

You can trigger the change event after the adding the handler. A namespaced event handler is used since we don't want any other handler to get executed.

您可以在添加处理程序后触发更改事件。使用命名空间事件处理程序是因为我们不希望执行任何其他处理程序。

$(document).ready(function() {
  $('#country').on('change.states', function() {
    $("#states").toggle($(this).val() == 'USA');
  }).trigger('change.states');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="country">
  <option value="" disabled="disabled" selected="selected">PLEASE CHOOSE</option>
  <option value="USA">USA</option>
  <option value="UK">UK</option>
  <option value="IT">ITALY</option>
</select>
<div id="states">states</div>

回答by Ehsan Sajjad

Just trigger change :

只需触发更改:

$('#country').on('change', function() {
  if ( this.value == 'USA')
    $("#states").show();     
  else
    $("#states").hide();
}).trigger("change"); // notice this line