显示基于选择值隐藏多个div [英] Show hide multiple divs based on select value

查看:74
本文介绍了显示基于选择值隐藏多个div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

寻找一些jQuery帮助以我创建的简单形式隐藏和显示内容.

Looking for some jQuery to help hide and reveal content in a simple form I'm creating.

选择字段中的选择选项1-3应该显示三个数据响应div之一,并显示其余形式的内容(数据形式顺序2).

Picking options 1-3 in the select field should show one of the three data response divs as well as reveal the content in the rest of the form (data-form-order 2).

我认为数据属性将是一个很好的选择,但对从何处开始却不确定.

I think data attributes would be a good route to go down but a little unsure of where to start.

<form>
  <div data-form-order="1">

    <div id="opening-question">
      <select id="select-box">
      <option value="0">- please select -</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>
    </div>

    <div data-response="op1">
      This is content for option 1.
    </div>
    <div data-response="op2">
      This is content for option 2.
    </div>
    <div data-response="op3">
      This is content for option 3.
    </div>
  </div>

  <div data-form-order="2" id="other-questions">
    Rest of form content. This area should show when option values 1-3 are selected in the select field.
  </div>
</form>

推荐答案

真正需要做的就是默认情况下使用某些CSS隐藏所有div,然后使用change函数获取值并选择基于div的在该值上:

Really all you need is to hide all the divs using some CSS by default, and then use the change function to get the value and select the div based on that value:

$('#select-box').change(function(){

   var selectVal = $(this).val();
   $('.content, #other-questions').hide();
   $('.content[data-response="op' + selectVal + '"], #other-questions').show();

});

.content, #other-questions {
display: none;
}

<script src="//code.jquery.com/jquery-3.2.1.min.js"></script>

<form>
  <div data-form-order="1">

    <div id="opening-question">
      <select id="select-box">
      <option value="0">- please select -</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>
    </div>

    <div class="content" data-response="op1">
      This is content for option 1.
    </div>
    <div class="content" data-response="op2">
      This is content for option 2.
    </div>
    <div class="content" data-response="op3">
      This is content for option 3.
    </div>
  </div>

  <div data-form-order="2" id="other-questions">
    Rest of form content. This area should show when option values 1-3 are selected in the select field.
  </div>
</form>

我更新了答案,添加了比数据属性更适合选择元素的类.

I've updated my answer to include classes which are better for selecting elements than data attributes.

这篇关于显示基于选择值隐藏多个div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆