根据选择值显示/隐藏字段

Udd*_*ers 14 javascript php jquery

我试图显示和隐藏一些表单字段,具体取决于我的一个选择字段的值.我希望使用数组来保存应该显示的内容和不应该为每个选择值显示的内容,以便从庞大的switch语句中保存,但无法弄清楚如何执行它.

我正在使用PHP和jQuery.任何帮助都会很棒.

ben*_*wey 33

尝试这样的事情:

<select id="viewSelector">
   <option value="0">-- Select a View --</option>       
   <option value="view1">view1</option>
   <option value="view2">view2</option>
   <option value="view3">view3</option>
</select>

<div id="view1">
  <!-- content --> 
</div>
<div id="view2a">
  <!-- content --> 
</div>
<div id="view2b">
  <!-- content --> 
</div>
<div id="view3">
  <!-- content --> 
</div>
Run Code Online (Sandbox Code Playgroud)

然后在jQuery中:

$(document).ready(function() {
  $.viewMap = {
    '0' : $([]),
    'view1' : $('#view1'),
    'view2' : $('#view2a, #view2b'),
    'view3' : $('#view3')
  };

  $('#viewSelector').change(function() {
    // hide all
    $.each($.viewMap, function() { this.hide(); });
    // show current
    $.viewMap[$(this).val()].show();
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 这很美妙..有点喜欢Jquerry,以及那些制作这样的例子的人 (2认同)

Jam*_*mes 5

有几种不同的方法可以做到这一点.最简单的是有几个单独的字段集,每个字段集包含一组字段.然后,在jQuery中,依赖于select-menu的值,您可以显示/隐藏这些字段集,例如

<fieldset id="f1">
    <input name="something1" />
    <input name="something2" />
    <input name="something3" />
</fieldset>
<fieldset id="f2">
    <input name="something4" />
    <input name="something5" />
    <input name="something6" />
</fieldset>
<select name="fieldset-choice">
    <option value="f1">Fieldset 1</option>
    <option value="f2">Fieldset 2</option>
</select>

<script type="text/javascript">
    jQuery('select[name=fieldset-choice]').change(function(){
        var fieldsetName = $(this).val();
        $('fieldset').hide().filter('#' + fieldsetName).show();
    });

    // We need to hide all fieldsets except the first:
    $('fieldset').hide().filter('#f1').show();
</script>
Run Code Online (Sandbox Code Playgroud)

注意:要使上述技术完全不引人注意,您可能需要使用所有不同字段集的名称动态构建选择菜单.


或者,您可以使用有意义的前缀为每个字段名称添加前缀,然后根据该属性隐藏/显示:

<input name="group1-name1" />
<input name="group1-name2" />

<input name="group2-name3" />
<input name="group2-name4" />
<input name="group2-name5" />

<select name="field-choice">
    <option value="group1">Group 1</option>
    <option value="group2">Group 2</option>
</select>

<script type="text/javascript">
    jQuery('select[name=field-choice]').change(function(){
        var groupName = $(this).val();
        $('input').hide().filter('[name^=' + groupName + ']').show();
    });

    // We need to hide all fields except those of the first group:
    $('input').hide().filter('[name^=group1]').show();
</script>
Run Code Online (Sandbox Code Playgroud)