Change the content of a div based on selection from dropdown menu - javascript

Is there a simple way, using JavaScript, to dynamically show/hide content in a <div> based on the users selection from a drop down menu? For example, if a user selects option 1 then I would like <div> 1 to be displayed and all other <div>s to be hidden.
EDIT: Example HTML Setup
<select>
<option> Option 1</option>
<option> Option 2</option>
<option> Option 3</option>
<select>
<div id="content_1" style="display:hidden;">Content 1<div>
<div id="content_2" style="display:hidden;">Content 2<div>
<div id="content_3" style="display:hidden;">Content 3<div>

The accepted answer has a couple of shortcomings:
Don't target IDs in your JavaScript code. Use classes and data attributes to avoid repeating your code.
It is good practice to hide with CSS on load rather than with JavaScript—to support non-JavaScript users, and prevent a show-hide flicker on load.
Considering the above, your options could even have different values, but toggle the same class:
<select class="div-toggle" data-target=".my-info-1">
<option value="orange" data-show=".citrus">Orange</option>
<option value="lemon" data-show=".citrus">Lemon</option>
<option value="apple" data-show=".pome">Apple</option>
<option value="pear" data-show=".pome">Pear</option>
</select>
<div class="my-info-1">
<div class="citrus hide">Citrus is...</div>
<div class="pome hide">A pome is...</div>
</div>
jQuery:
$(document).on('change', '.div-toggle', function() {
var target = $(this).data('target');
var show = $("option:selected", this).data('show');
$(target).children().addClass('hide');
$(show).removeClass('hide');
});
$(document).ready(function(){
$('.div-toggle').trigger('change');
});
CSS:
.hide {
display: none;
}
Here's a JSFiddle to see it in action.

here is a jsfiddle with an example of showing/hiding div's via a select.
HTML:
<div id="option1" class="group">asdf</div>
<div id="option2" class="group">kljh</div>
<div id="option3" class="group">zxcv</div>
<div id="option4" class="group">qwerty</div>
<select id="selectMe">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
jQuery:
$(document).ready(function () {
$('.group').hide();
$('#option1').show();
$('#selectMe').change(function () {
$('.group').hide();
$('#'+$(this).val()).show();
})
});

With zero jQuery
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style>
.inv {
display: none;
}
</style>
<body>
<select id="target">
<option value="">Select...</option>
<option value="content_1">Option 1</option>
<option value="content_2">Option 2</option>
<option value="content_3">Option 3</option>
<select>
<div id="content_1" class="inv">Content 1</div>
<div id="content_2" class="inv">Content 2</div>
<div id="content_3" class="inv">Content 3</div>
<script>
document
.getElementById('target')
.addEventListener('change', function () {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementById(this.value);
if (vis !== null) {
vis.className = 'inv';
}
if (target !== null ) {
target.className = 'vis';
}
});
</script>
</body>
</html>
Codepen
document
.getElementById('target')
.addEventListener('change', function () {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementById(this.value);
if (vis !== null) {
vis.className = 'inv';
}
if (target !== null ) {
target.className = 'vis';
}
});
.inv {
display: none;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<select id="target">
<option value="">Select...</option>
<option value="content_1">Option 1</option>
<option value="content_2">Option 2</option>
<option value="content_3">Option 3</option>
<select>
<div id="content_1" class="inv">Content 1</div>
<div id="content_2" class="inv">Content 2</div>
<div id="content_3" class="inv">Content 3</div>
</body>
</html>

Meh too slow. Here's my example anyway :)
http://jsfiddle.net/cqDES/
$(function() {
$('select').change(function() {
var val = $(this).val();
if (val) {
$('div:not(#div' + val + ')').slideUp();
$('#div' + val).slideDown();
} else {
$('div').slideDown();
}
});
});

I am not a coder, but you could save a few lines:
<div>
<select onchange="if(selectedIndex!=0)document.getElementById('less_is_more').innerHTML=options[selectedIndex].value;">
<option value="">hire me for real estate</option>
<option value="me!!!">Who is a good Broker? </option>
<option value="yes!!!">Can I buy a house with no down payment</option>
<option value="send me a note!">Get my contact info?</option>
</select>
</div>
<div id="less_is_more"></div>
Here is demo.

There are many ways to perform your task, but the most elegant are, I believe, using css.
Here are basic steps
Listening option selection event, biding adding/removing some class to container action, which contains all divs you are interested in (for example, body)
Adding styles for hiding all divs except one.
Well done, sir.
This works pretty well if there a few divs, since more elements you want to toggle, more css rules should be written. Here is more general solution, binding action, base on following steps:
1. find all elements using some selector (usually it looks like '.menu-container .menu-item')
2. find one of found elements, which is current visible, hide it
3. make visible another element, the one you desire to be visible under new circumstances.
javascript it a rather timtoady language )

Related

Show hide multiple divs based on select value

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>

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>

Conditional Form with Javascript

I'm creating a form where certain fields should only show depending on the initial product selected, here's the JS i have:
<script type='text/javascript' src='http://code.jquery.com/jquery-1.6.4.js'></script>
<script type='text/javascript'>
//<![CDATA[
$(window).load(function() {
$("#product").change(function() {
var selected = $("#product option:selected").text();
$('div').hide();
$('#' + selected).show();
});
$(document).ready(function() {
$('div').hide();
});
}); //]]>
</script>
and here is the HTML so far:
<select id="product">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
<div id="1">Options that are available for Product 1</div>
<div id="2">Options that are available for Product 2</div>
<div id="3">Options that are available for Product 3</div>
<div id="4">Options that are available for Product 4</div>
<div id="5">Options that are available for Product 5</div>
<div id="6">Options that are available for Product 6</div>
<div id="7">Options that are available for Product 7</div>
The problem i'm having is that in the options (1/2/3/4/5/6/7) these need to be product names, but it doesnt work without the numbers in there. So for example 1 should be called Product 1, 2 should be called Product 2, and so forth.
Can you help?
jsFiddle
JS
$(document).ready(function () {
$("#product").change(function () {
var selected = $("#product option:selected").val();
$('div').hide();
$('#' + selected).show();
});
$('div').hide();
});
Description
By using .val() instead of .text() you will be getting the option's value. This let's you show the user anything like Screwdriver instead of Product 1.
The removal of the following code is because it is duplicate of $(document).ready(function () {:
$(window).load(function() {
Although the functionality differs in this situation there isn't a benefit of both usages.
HTML
<select id="product">
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
<option value="4">Product 4</option>
<option value="5">Product 5</option>
<option value="6">Product 6</option>
<option value="7">Product 7</option>
</select>
<div id="1">Options that are available for Product 1</div>
<div id="2">Options that are available for Product 2</div>
<div id="3">Options that are available for Product 3</div>
<div id="4">Options that are available for Product 4</div>
<div id="5">Options that are available for Product 5</div>
<div id="6">Options that are available for Product 6</div>
<div id="7">Options that are available for Product 7</div>
var selected= $("#product option:selected").val();
Try it please.
Use .val() instead of .text()
var selected = $("#product").val();
DEMO
USE:
var selected = $("#product option:selected").val();
What I suggest is doing the following:
Create a container div for all of the different product-related forms
Listen for change events on the select box
When a select event is caught, hide all of the children in the container div and then show the one that has been selected.
I also suggest that you decouple the product form configuration from the value of the select box, so that you have greater freedom as far as controlling your form.
A working example (jsfiddle)
HTML
<body>
<select id="selector">
<option data-for="p1-form">Product 1</option>
<option data-for="p2-form">Product 2</option>
<option data-for="p3-form">Product 3</option>
</select>
<div id="product-forms">
<div id="p1-form" class="product-form">
Product 1 form
</div>
<div id="p2-form" class="product-form">
Product 2 form
</div>
<div id="p3-form" class="product-form">
Product 3 form
</div>
</div>
</body>
CSS
.product-form {
display: none;
}
JS
var $selector = $('#selector');
var $productForms = $('#product-forms');
$selector.change(function () {
var toEnable = $('option:selected', $selector).data('for');
$productForms.children().css('display', 'none');
$('#' + toEnable).css('display', 'block');
}).change();

Javascript Help about "document.getElementById" please

Here's my code:
<html>
<head>
<script>
function changeDate(option) {
var selectList = document.getElementById("catProdAttributeItem");
if (option == 0) {
selectList.selectedIndex++;
} else if (option == 1 && selectList.selectedIndex > 0) {
selectList.selectedIndex--;
}
}
</script>
</head>
<body>
<img src="img1.jpg" onclick="changeDate(0)">
<img src="img2.jpg" onclick="changeDate(1)">
<select id="pa_colour" name="attribute_pa_colour">
<option value="">Choose an option…</option>
<option value="black" class="active">Black</option>
<option value="blue" class="active">Blue</option>
<option value="red" class="active">Red</option>
<option value="white" class="active">White</option>
</select>
<div id="catProdAttributeItem">
<select>
<option id="1">One</option>
<option id="2">Two</option>
<option id="3">three</option>
<option id="4">Four</option>
</select>
</div>
</body>
</html>
In this code what I want to do is when the user clicks an image, the select option value will change.
If the <select id="list"> select has an id it will work fine, but in my case, the select option has no id, but before the select there is a class "catProdAttributeItem".
How do I make it work with document.getElementById and select option?
Select element is the child of Div, so you need to access the child element. For that,use following :
var selectList = document.getElementById("catProdAttributeItem").children[0];
Here is the working demo : http://jsfiddle.net/spdX3/
Since the select element is within the catProdAttributeItem div, you can select it using the childNodes property
var selectList = document.getElementById("catProdAttributeItem").childNodes[0];
Rest of the code should work as it is.

Show divs based on dropdown - Script not working

I'm trying to show div's based on dropdown selection using the following script.
It works perfectly on a simple page without any thing in it; but when I put it in the page that I'm developing, it messes up the entire page, making it black and at the end of the URL I get this ...../myPage.html#someIdInThePage .
JS:
<script type="text/javascript">
$(document).ready(function () {
function showTheTab(name) {
name = '#' + name;
$('div').not(name).hide();
$(name).show();
}
$('#dropdown').change(function () {
showTheTab($(this).val());
});
showTheTab($('#dropdown').val());
});
</script>
HTML:
<form>
<p>
<select id="dropdown" name="dropdown">
<option value="Pubs" selected="selected">Pubs</option>
<option value="Councils">Councils</option>
<option value="Property">Property</option>
<option value="Various">Various</option>
<option value="Universitys">Universitys</option>
</select>
</p>
</form>
<div id="Pubs">pubs</div>
<div id="Councils">councils</div>
<div id="Property">property</div>
<div id="Various">various</div>
<div id="Universitys">universitys</div>
This line: $('div').not(name).hide(); will hide every div on your page apart from the selected div. You're going to need a more specific selector to do the hiding
Example
Javascript:
$(document).ready(function () {
function showTheTab( name )
{
name = '#' + name;
$('div.Tabs > div').not(name).hide();
$(name).show();
}
$('#dropdown').change( function() {
showTheTab( $( this ).val() );
});
showTheTab( $('#dropdown').val() );
});
Html:
<form>
<p>
<select id="dropdown" name="dropdown">
<option value="Pubs" selected="selected">Pubs </option>
<option value="Councils">Councils </option>
<option value="Property">Property </option>
<option value="Various">Various </option>
<option value="Universitys">Universitys </option>
</select>
</p>
</form>
<div class="Tabs">
<div id="Pubs">pubs</div>
<div id="Councils">councils</div>
<div id="Property">property</div>
<div id="Various">various</div>
<div id="Universitys">universitys</div>
</div>

Categories