【问题标题】:Show/hide fields depending on select value根据选择值显示/隐藏字段
【发布时间】:2023-03-22 12:35:02
【问题描述】:

我正在尝试根据我的选择字段之一的值显示和隐藏一些表单字段。我希望使用数组来保存每个选择值应该显示和不应该显示的内容,以使我免于大量 switch 语句,但无法弄清楚如何去做。

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

【问题讨论】:

    标签: php javascript jquery


    【解决方案1】:

    试试这样的:

    <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>
    

    然后在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();
      });
    });
    

    【讨论】:

    • 抱歉早点发帖,手指在键盘上打滑了。看起来我对此投了反对票。
    • 应该 this.hide();替换为 $(this).hide();
    • 我对此进行了测试,它可以工作。请注意,您最初可能需要隐藏视图/显示默认值。
    • @Jose,不是来自我的测试。这已经是包装好的集合对象了。
    • 效果很好.. 一定要爱 Jquery 和那些制作这样的例子的人
    【解决方案2】:

    有几种不同的方法可以做到这一点。最简单的方法是拥有几个单独的字段集,每个字段集包含一组字段。然后,在 jQuery 中,根据选择菜单的值,您可以显示/隐藏这些字段集,例如

    <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>
    

    注意:为了使上述技术完全不引人注目,您可能希望使用所有不同字段集的名称动态构建选择菜单。


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

    <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>
    

    【讨论】:

      【解决方案3】:

      要在加载时启动代码,只需添加 .change()。如下图...

      $(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();
        }).change();
      });
      

      【讨论】:

        【解决方案4】:

        我的 2 美分: 我需要根据许多先前的选择值(不仅仅是一个)来显示/隐藏字段。

        所以我向这样的 div 字段添加了一个父属性:

        <div id="view" parent="none">
        <select class=selector id="view">
        <option value="0"> -- Make a choice --</option>
        <option value="s1">sub 1</option>
        <option value="s2">sub 2</option>
        <option value="s3">sub 3</option>
        </select>
        </div>
        
        <!-- you need to define the parent value with the value of parent div id -->
        <div id="s1" parent="view">
        <!-- if you want to have a selector be sure it has the same id as the div -->
        <select class=selector id="s1">
        <option value="0">-- Make a choice --</option>
        <option value="s1_sub1">sub 1 of s1</option>
        <option value="s1_sub2">sub 2 of s1</option>
        <option value="s1_sub3">sub 3 of s1</option>
        </select>
        </div>
        
        <!-- Make the same thing for s2 and s3
        Define div s2 here
        
        Define div s3 here
        -->
        
        <!-- and finally if that's your final step you put what you want in the div -->
        <div id="s1_sub1" parent="s1">
        You are inside s1 sub1
        </div>
        

        现在是 jquery 代码:

        $(document).ready(function() {
        
         $('select[class=selector]').change(function() { 
            //next div to show
            var selectorActive = $(this).val();
            //div where you are 
            var parentValue = $(this).attr("id");
        
           //show active div and hide others
            $('div').hide().filter('#' + selectorActive).show();
        
            while (parentValue!="none") {
              //then show parents of active div
              $('div[id=' + parentValue + ']').show();
              //return the parent of div until "none"
              parentValue = $('div[id=' + parentValue + ']').attr("parent");
             }
        
         });
        
        // print only the first div at start
         $('div').hide().filter("#view").show();
        
        });
        

        这就像一个魅力,你不需要定义地图

        我希望这会有所帮助

        【讨论】:

          【解决方案5】:

          @Martin 试试这个

          `$('#viewSelector').trigger('change');`
          

          【讨论】:

            【解决方案6】:

            这是一个非常简单的例子:

            目的是展示一个简单示例,说明如何根据选择的值使用值数组来显示/隐藏字段。

            在这个演示中,我可以使用类名来一次性显示/隐藏字段组——但这不是示例的目的——所以使用了类名仅适用于 CSS。

            因为demo使用了ID(这些ID的两个数组),所以要隐藏的字段是input字段,divs,@987654323都没有关系@ 或你有什么。 ID 标识要隐藏的内容。

            var aPeople = ['bob','sam','ted'];
            var aTransport = ['car','bike','truck'];
            
            $('#mySel').change(function(){
               $('.alldiv').hide(); //Hide them all to start...
               let sel = $(this).val(); //Get selected option value
               if ( sel=='ppl' ){
                  for (let i=0; i<aPeople.length;i++){
                     $('#' + aPeople[i]).show();
                  }
               }else if ( sel=='tpt' ){
                  for (let i=0; i<aTransport.length;i++){
                     $('#' + aTransport[i]).show();
                  }
               }else{
                  //Choose selected
                  $('.alldiv').show();
               }
            });
            .alldiv{width:30vw;height:10vh;padding:2vh 2vw;text-align:center;}
            .ppl{background:palegreen;}
            .tpt{background:wheat;}
            <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
            
            <select id="mySel">
              <option value="">Choose:</option>
              <option value="ppl">People</option>
              <option value="tpt">Vehicles</option>
            </select>
            
            <div id="bob" class="alldiv ppl">People: Bob</div>
            <div id="car" class="alldiv tpt">Vehicle: Car</div>
            <div id="truck" class="alldiv tpt">Vehicle: Truck</div>
            <div id="sam" class="alldiv ppl">People: Sam</div>
            <div id="ted" class="alldiv ppl">People: Ted</div>
            <div id="bike" class="alldiv tpt">Vehicle: Bike</div>

            【讨论】:

              猜你喜欢
              • 2017-02-02
              • 2019-10-19
              • 2022-01-18
              • 1970-01-01
              • 2011-06-26
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多