Show hide multiple divs based on select value - javascript

Looking for some jQuery to help hide and reveal content in a simple form I'm creating.
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>

I highly recommend reading Decoupling Your HTML, CSS, and JavaScript. You can make some really simple and reusable jQuery that does some pretty cool stuff, without a lot of duplicate code or tightly coupled code. The following is very extensible, reusable, easy to read and maintain.
$(document).ready(()=>{
$('.js-revealer').on('change', function(){
var $select = $(this);
var $selected = $select.find('option:selected');
var hideSelector = $selected.data('r-hide-target');
var showSelector = $selected.data('r-show-target');
$(hideSelector).addClass('is-hidden');
$(showSelector).removeClass('is-hidden');
});
});
.is-hidden{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div data-form-order="1">
<div id="opening-question">
<select id="select-box" class="js-revealer">
<option value="0" data-r-show-target="" data-r-hide-target=".opt-1, .opt-2, .opt-3, .opt-other">- please select -</option>
<option value="1" data-r-show-target=".opt-1, .opt-other" data-r-hide-target=".opt-2, .opt-3">Option 1</option>
<option value="2" data-r-show-target=".opt-2, .opt-other" data-r-hide-target=".opt-1, .opt-3">Option 2</option>
<option value="3" data-r-show-target=".opt-3, .opt-other" data-r-hide-target=".opt-1, .opt-2">Option 3</option>
</select>
</div>
<div data-response="op1" class="opt-1 is-hidden">
This is content for option 1.
</div>
<div data-response="op2" class="opt-2 is-hidden">
This is content for option 2.
</div>
<div data-response="op3" class="opt-3 is-hidden">
This is content for option 3.
</div>
</div>
<div data-form-order="2" id="other-questions" class="opt-other is-hidden">
Rest of form content. This area should show when option values 1-3 are selected in the select field.
</div>
</form>

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.

I would suggest using classes for this, there is no need for data attributes.
$(function() {
$('#select-box').change(function(){
if($('#select-box').val() == '1') {
$('.response1').show();
$('.response2').hide();
$('.response3').hide();
$('#content').show();
}
else if($('#select-box').val() == '2') {
$('.response1').hide();
$('.response2').show();
$('.response3').hide();
$('#content').show();
}
else if($('#select-box').val() == '3') {
$('.response1').hide();
$('.response2').hide();
$('.response3').show();
$('#content').show();
}
});
});
.response1, .response2, .response3 {
display: none;
}
#content {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.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='response1' data-response="op1">
This is content for option 1.
</div>
<div class='response2' data-response="op2">
This is content for option 2.
</div>
<div class='response3' data-response="op3">
This is content for option 3.
</div>
</div>
<div id='content' 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 have shown show/hide using Class . Initially hide all div's , shown on drop down selection (only matches div).Here is how.I have created two classes hide
to hide the element and show to show the element.
$('[data-response^=op]').attr('class',"hide");//Initially set all div hidden
$("#select-box").on("change",function(){
var value = $(this).val();
if(value !="" && value<=3 && value !=0){
console.clear();// to clear older logs.
console.log('Selected value'+$(this).val());
$('[data-response^=op]').attr('class',"hide");//On change hide all div's
var selector = "op"+value;
$(document).find("[data-response='"+selector+"']").attr('class',"show");
$("#other-questions").attr('class',"show");//Show matching div.
}else{
$("#other-questions").attr('class',"hide");
$('[data-response^=op]').attr('class',"hide");
}
})
.hide{
display:none;
}
.show{
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.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 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" class="hide">
Rest of form content. This area should show when option values 1-3 are selected in the select field.
</div>
</form>

Related

How to show content (<div>) as per selection options (<select>)?

I want to show content based on user's selection from <select> <option>.
Like, when user selects the <option value="Option A"> then only show the <div> containing "Orange".
HTML:
`
<div id="main-container">
<select name="" id="user-selector" class="selector-dropdown">
<option selected="true" style='display: none'>Select</option>
<option value="Option A">Fruit</option>
<option value="Option B">Animal</option>
<option value="Option C">Language</option>
<option value="Option C">Stationary</option>
</select>
<div class="output">Orange</div>
<div class="output">Lion</div>
<div class="output">English</div>
<div class="output">Pen</div>
</div>
`
I have searched in codepen, stackoverflow, and most were using jQuery which i couldn't understand.
It's been 2 days I've started learning JS. It really helps if you can help me the JS code.
Thanks in advance!
What you will need to do is create an event listener for the select that listens for its change.
I created a class called active that will show the div. By default I have css style for output that sets it as display none.
Then in the event listener, the first thing I do is remove the active class if it exists.
Also I add the value of the options as data attributes to the divs. This allows you to reference that div.
Then simply add the new active class to that div.
let selector = document.querySelector(".selector-dropdown");
selector.addEventListener("change", (e) => {
let active = document.querySelector(".output.active");
if (active) active.classList.remove("active");
let _target = document.querySelector("[data-option='" + e.target.value + "']")
if (_target) _target.classList.add("active");
});
.output {
display: none;
}
.output.active {
display: block;
}
<div id="main-container">
<select name="" id="user-selector" class="selector-dropdown">
<option selected="true" style='display: none'>Select</option>
<option value="Option A">Fruit</option>
<option value="Option B">Animal</option>
<option value="Option C">Language</option>
<option value="Option D">Stationary</option>
</select>
<div data-option="Option A" class="output">Orange</div>
<div data-option="Option B" class="output">Lion</div>
<div data-option="Option C" class="output">English</div>
<div data-option="Option D" class="output">Pen</div>
</div>

click only the header not its specified children

I have this html
<div class="accordion_wrapper">
<div class="accordion_header">
<h1>Accordion Test</h1>
<select>
<option value="" selected disabled>Options</select>
<option value="option 1">Option 1</option>
<option value="option 2">Option 2</option>
<option value="option 3">Option 3</option>
</select>
</div> <!-- end of accordion header -->
<div class="accordion_content">
<p>this is the accordion content</p>
</div>
</div> <!-- end of accordion wrapper -->
and this script
//already integrated the required jquery
//already on document ready
$('.accordion_header').bind({
click: function () {
var $sub = $(this).next('.accordion_content').stop(true, true);
if ($sub.is(':visible')) {
$sub.slideUp();
} else {
$sub.slideDown();
}
}
});
everything works, however if I click the select box (dropdown stuff) the click function of the .accordion_header is also triggered which I dont want it to trigger if I click the select box. Any clues, ideas, suggestions, recommendations, help to stop/prevent the .accordion_header being triggered when select box is click?
Below is my snippet
//already integrated the required jquery
//already on document ready
$('.accordion_content').hide();
$('.accordion_header').bind({
click: function () {
var $sub = $(this).next('.accordion_content').stop(true, true);
if ($sub.is(':visible')) {
$sub.slideUp();
} else {
$sub.slideDown();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="accordion_wrapper">
<div class="accordion_header">
<h1>Accordion Test</h1>
<select>
<option value="" selected disabled>Options</option>
<option value="option 1">Option 1</option>
<option value="option 2">Option 2</option>
<option value="option 3">Option 3</option>
</select>
</div> <!-- end of accordion header -->
<div class="accordion_content">
<p>this is the accordion content</p>
</div>
</div> <!-- end of accordion wrapper -->
You need to stop event propagation to child elements.
Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
$('select').click(function(e){
e.stopPropagation();
});

Change the CSS attribute if an option selected with jQuery

I have this code:
<select>
<option disabled selected>Select Method</option>
<option value="question">Question</option>
<option value="password">Password</option>
<option value="email">Email</option>
<option value="none">None</option>
</select>
Now I want when user select each of them some div that hidden in css with display:none; get visible for example when user select Question the div that have question id get visible or when Password selected the div that have password id get visible.
I try this but not work:
$(document).ready(function(){
if ($("#auth option:selected").text() == "question"){
$("#question").css("display","block");
}
});
So how can I do this?
If you follow the pattern you have done so far, you have to write code for each option. If your options and div elements are coupled with value and id, you can simply do like this,
$("select").change(function() {
$("div").hide();
$("#" + $(this).val()).show();
});
Demo Fiddle
Here is Demo for this , remove disabled from select tag so that user can select the options
Jsfiddle
http://jsfiddle.net/adarshkr/z9gcf40r/2/
Code
HTML
<select id="showdiv">
<option disabled selected>Select Method</option>
<option value="question">Question</option>
<option value="password">Password</option>
<option value="email">Email</option>
<option value="none">None</option>
</select>
<div id="question" class="hide">
<p>question</p>
</div>
<div id="password" class="hide">
<p>password</p>
</div>
<div id="email" class="hide">
<p>email</p>
</div>
<div id="none" class="hide">
<p>none</p>
</div>
CSS
.hide{
display:none
}
JAVASCRIPT
$("select").change(function(){
$("div").hide();
$("#"+$(this).val()).show();
});
try this,
$('#auth').on('change', function() {
var that = $(this).val();
if (that === "question"){
$("#question").css("display","block");
}
});
Better check value than the text.
$(document).ready(function(){
if ($("#auth option:selected").val() == "question"){
$("#question").css("display","block");
}
});

Show relevant divs when an html select option is clicked

I want a div to become visible when its corresponding select option is clicked (and to hide others) unfortunately my attempts at JavaScript are terrible.
CSS
#aaa, #bbb, #ccc {
display:none;
}
The HTML (I use the same id name for option and div - is this incorrect?)
<select>
<option>Select</option>
<option id="aaa" value="aaa" onclick="showExtra(this)">AAA</option>
<option id="bbb" value="bbb" onclick="showExtra(this)">BBB</option>
<option id="ccc" value="ccc" onclick="showExtra(this)">CCC</option>
</select>
<div id="aaa">
<p>AAA is aaamazing</p>
</div>
<div id="bbb">
<p>BBB is bbbriliant</p>
</div>
<div id="ccc">
<p>cccor blimey CCC</p>
</div>
The JavaScript
function showExtra(element)
{
I don't have clue .slideToggle("medium");
}
Get rid of the IDs in the <option> elements, they're not needed (or if they are, you need to rename them, e.g. optaaa, so they don't conflict with the IDs of the DIVs). Also, call the function from the dropdown's onchange event, not clicking on the options.
<select onchange="showExtra(this)">
<option>Select</option>
<option value="aaa">AAA</option>
<option value="bbb">BBB</option>
<option value="ccc">CCC</option>
</select>
Give all your DIVs a class, so you can operate on them as a group:
<div id="aaa" class="tab">
<p>AAA is aaamazing</p>
</div>
<div id="bbb" class="tab">
<p>BBB is bbbriliant</p>
</div>
<div id="ccc" class="tab">
<p>cccor blimey CCC</p>
</div>
In the JS, you can then operate on all the DIVs that do or don't match the value.
function showExtra(option) {
var divID = option.value;
$(".tab:not(#"+divID+")").slideUp();
$(".tab#"+divID).slideDown();
}
DEMO

force Select option to default on page load

I have a select box that uses JS to hide/show divs based on selection. The challenge I have is that when the page is reloaded it defaults to the last selection (and no associated div) rather than the default.
CSS:
#div1,#div2,#div3 {
display: none
}
JS:
function showHide(elem) {
if(elem.selectedIndex != 0) {
//hide the divs
for(var i=0; i < divsO.length; i++) {
divsO[i].style.display = 'none';
}
//unhide the selected div
document.getElementById('div'+elem.value).style.display = 'block';
}
}
window.onload=function() {
//get the divs to show/hide
divsO = document.getElementById("frmMyform").getElementsByTagName('div');
}
HTML:
<form action="#" method="post" id="frmMyform">
<select name="selMyList" onchange="showHide(this)">
<option value="">Select an option</option>
<option value="1">Show div 1</option>
<option value="2">Show div 2</option>
<option value="3">Show div 3</option>
</select>
<div id="div1">This is Div 1</div>
<div id="div2">This is Div 2</div>
<div id="div3">This is Div 3</div>
</form>
I tried setting #div0 to hidden and then adding it to the list of divs but it does'nt seem to work. Also tried using jquery but this is a WordPress site and one of the plugin's interferes with this functionality. This is very close to working perfectly, but just need to resolve this weirdness.
Any ideas?
Try to use selected attribute for option tag:
<select name="selMyList" onchange="showHide(this)">
<option value="" selected="selected">Select an option</option>
<option value="1">Show div 1</option>
<option value="2">Show div 2</option>
<option value="3">Show div 3</option>
</select>

Categories