force Select option to default on page load - javascript

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>

Related

Multiple drop down boxes?

I'm trying to get multiple drop down boxes to open when selecting different prompts from an original drop down menu.
So for example the original drop box would say "Continent" then drop down to a list of continents, when you select a continent a new box opens that asks you "Country" then you select a country and a new drop box opens to select a state.
I've been using this template
<script type="text/javascript">
function CheckDepartment(val){
var element=document.getElementById('othercolor');
if(val=='others')
element.style.display='block';
else
element.style.display='none';}
function CheckOption(val){
var element=document.getElementById('misc')
if(val=='misc')
element.style.display='block';
else
element.style.display='block';
}
</script>
</head>
<body>
<select name="color" onchange='CheckDepartment(this.value);'>
<option>pick a color</option>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="others">others</option>
</select>
<select name="othercolor" id="othercolor" onchange='CheckOption(this.value)' style='display:none;'/>
<option value=""></option>
<option value="hi">hi</option>
<option value="misc" id="misc" >misc</option>
</select>
<select name="third" style='display:none;'>
<option value=""></option>
<option value="first">first</option>
<option value="second">second</option>
</select>
but I can't get a third drop box to open when selecting an option from the second drop box.
edit: third box. I think i deleted my last try so this was kinda a recreation of it from what I remembered. I'm also incredibly new at all of this and don't know if anything I tried makes sense.
Here's a simplified demo.
(It assumes only a "yes" value should trigger the display of the next dependent dropdown.)
const
select1 = document.getElementById("select1"),
select2 = document.getElementById("select2");
document.addEventListener("change", handleDropdownDisplay);
function handleDropdownDisplay(event) {
let changedElement = event.target;
if ((changedElement != select1) && (changedElement != select2)) {
return;
}
if (changedElement.value == "yes") {
changedElement.parentElement.nextElementSibling.classList.remove("hidden");
} else {
changedElement.parentElement.nextElementSibling.classList.add("hidden");
}
}
div {
margin-bottom: 0.5em;
}
.hidden {
display: none;
}
<div>
<label for="select1">Show level 2?</label>
<select id="select1">
<option value="no">No</option>
<option value="yes">Yes</option>
</select>
</div>
<div class="hidden">
<label for="select2">Show level 3?</label>
<select id="select2">
<option value="no">No</option>
<option value="yes">Yes</option>
</select>
</div>
<div class="hidden">
<label for="select3">Would your rather</label>
<select id="select3">
<option value="brains">Eat monkey brains</option>
<option value="vba">Write code in VBA</option>
</select>
</div>
(Btw, level 3 doesn't automatically become hidden whenever level 2 becomes hidden. This is probably functionality you'll want to add.)

How to trigger an Event using an ID in a Select list

I have a select list that triggers DIV tag visibility, which works great, but once I added a new select list it started conflicting with the first list. I need to be able to use the first list to trigger the toggle event independently of any other lists in the code.
I'm to use the select list using a specific ID to properly toggle the DIV visibility but I can't seem to get it right.
$(document).ready(function () {
$("select").change(function () {
$(this).find("option:selected").each(function () {
var optionValue = $(this).attr("value");
if (optionValue) {
$(".divToggle").not("." + optionValue).hide();
$("." + optionValue).show();
} else {
$(".divToggle").hide();
}
});
}).change();
});
This is the select options:
<select id="transferOptions" class="form-control" name="transferoptions" aria-label="Transfer Options" tabindex="">
<option value="fundTransferOption" selected>Select an Option</option>
<option value="achTransfer">ACH Transfer</option>
<option value="flashFundsTransfer">Flash Transfer</option>
</select>
<select id="ConflictingSelectOptionsAlsoCausingDIVToggling">
<option>Choose</option>
<option>Blah</option>
<option>Blah 2</option>
</select>
<div class="achTransfer divToggle">On select show Thing 1</div>
<div class="flashFundsTransfer divToggle">On select show Thing 2</div>
I want to use the Javascript above to specifically work the select list that use the "id="transferOptions", so as I add other select lists to the code it won't conflict with the transferOptionselect list, thus triggering the DIV's in the page.
Use the select ID with its CSS selector #transferOptions. Also changed some logic for you to check out:
$(document).ready(function() {
$("#transferOptions").change(function() {
var optionValue = $(this).val(); // or use javascript: this.value
$(".divToggle").hide(); // hide all .divToggle elements
if (optionValue) { // in your example this is always true
$("." + optionValue).show(); // show the matching element
}
}).change(); // trigger change after document is ready
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="transferOptions" class="form-control" name="transferoptions" aria-label="Transfer Options" tabindex="">
<option value="fundTransferOption" selected>Select an Option</option>
<option value="achTransfer">ACH Transfer</option>
<option value="flashFundsTransfer">Flash Transfer</option>
</select>
<select id="ConflictingSelectOptionsAlsoCausingDIVToggling">
<option>Choose</option>
<option>Blah</option>
<option>Blah 2</option>
</select>
<div class="achTransfer divToggle">On select show Thing 1</div>
<div class="flashFundsTransfer divToggle">On select show Thing 2</div>
You can get the element that event is referring to using event.target instead of using this which in your case refers to the callback function, see example below:
$('select').change(event => {
console.log(event.target.id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select1">
<option>foo</option>
<option>bar</option>
<option>baz</option>
</select>
<select id="select2">
<option>quux</option>
<option>xyzzy</option>
</select>

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>

When Select Change Background Images Change

Hello I have a problem with html Select...When user will click one of the Value then background images have to change and appear a new Select and the old Select will disappear. I tried many things but it wasn't work...help me out please...
Here is the code:
<script>
$(document).ready(function(){
var header = $('body');
function SelectElement(valueToSelect)
{
var element = document.getElementById('test');
element.value = '1';
}
$(function() {
$('.test').click(function() {
var backgrounds = new Array(
'url(images/Main/1.png)'
, 'url(images/Main/2.jpg)'
, 'url(images/Main/3.jpg)'
, 'url(images/Main/4.jpg)'
, 'url(images/Main/5.jpg)'
, 'url(images/Main/6.jpg)'
, 'url(images/Main/7.jpg)'
, 'url(images/Main/8.jpg)'
, 'url(images/Main/9.jpg)'
, 'url(images/Main/10.jpg)'
);
});
});
var current = 0;
function nextBackground() {
current++;
current = current % backgrounds.length;
header.css('background-image', backgrounds[current]);
}
setInterval(nextBackground, 6000);
header.css('background-image', backgrounds[0]);
});
</script>
</head>
<body>
<center>
<div id="black">
<div style="margin-top:22%;margin-bottom:-22%;">
<form name="test">
<select id="test" name="test">
<option value="Select Season" selected="selected" disabled="disabled">Select Season..</option>
<option value="1" onclick="function()">Season 1</option>
<option value="Season 2">Season 2</option>
<option value="Season 3">Season 3</option>
<option value="Season 4">Season 4</option>
</select>
</form>
There are several issues with your current code - test is an id, not a class, so the selector is #test instead of .test
The array containing the images is not accessible from the function nextBackground(), as this array is defined in the function attached to the click event.
To be accessible for other function, it can be declared global.
I guess you don't want to change the image when select is clicked, but when an option is selected.
Maybe you want to change the background image according to the selected option - in this case it's possible to attach a function to the change() event of the select
and select the image from the background array with the index according to
the option value e.g. like this:
$('#test').change(function () {
header.css('background-image', backgrounds[$(this).val() -1]);
});
In addition, in your current code you call the function nextBackground() which
cycles through all background images.
I've just commented this out in the example Fiddle
Remaining question is how the new select that you want to display instead of the old select when an option is selected should be different from the old select, maybe
you can add this information to your question.
Your question is not entirely clear. The first (hidden) snippit below will set the background to the image that is stored in an array at the same index as the selected option and then show a different select box as you asked. But I get the feeling the second (showing) snippet is what you really need.
To better help you, please edit your question to include answers to the below questions:
Should the timer begin changing the backgrounds as soon as the
page loads?
What should happen when the first select box is changed
what should happen when the second select box is changed?
are we talking about the page body's background or some other div, or does each event control the background for a different div?
Are all of the pictures pulled from the same array or does each event have a different pool of source inmages?
$(document).ready(function(){
var header = $('body');
function SelectElement(valueToSelect)
{
var element = document.getElementById('test');
element.value = '1';
}
$('#test').change(function() {
// I did this with 4 images for testing, add as many as you like in yours
var backgrounds = ['url(http://stylonica.com/wp-content/uploads/2014/03/Nature___Seasons___Spring__038259_.jpg)'
, 'url(http://hd.wallpaperswide.com/thumbs/summer_holiday-t2.jpg)'
, 'url(http://www.grandfather.com/wp-content/uploads/2012/08/fall-road.jpg)'
, 'url(http://hooptricks.org/wp-content/uploads/2014/01/road-winter.jpg)'];
// get index of selected option
// -1 is to account for the disabled fist option acting as a placeholder
var cur = $(this)[0].selectedIndex -1;
// set the image to the background
header.css('background-image', backgrounds[cur]);
//hide the first select and show the second
$('#fisrtSelDiv').hide();
$('#secondSelDiv').show();
});
/*
// I commented the below out as it doesnt appear to be related to your question
// if you need the select to begin a timer that changes the backgrounds peridically
// please edit your question with more detail
var current = 0;
function nextBackground() {
current++;
current = current % backgrounds.length;
header.css('background-image', backgrounds[current]);
}
setInterval(nextBackground, 6000);
header.css('background-image', backgrounds[0]);
*/
});
#secondSelDiv{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="black">
<div style="margin-top:22%;margin-bottom:-22%;">
<div id="fisrtSelDiv">
<form name="test">
<select id="test" name="test">
<option value="" selected="selected" disabled="disabled">Select Season..</option>
<option value="Season 1">Season 1</option>
<option value="Season 2">Season 2</option>
<option value="Season 3">Season 3</option>
<option value="Season 4">Season 4</option>
</select>
</form>
</div>
<div id="secondSelDiv">
<form name="test2">
<select id="test2" name="test">
<option value="" selected="selected" disabled="disabled">Select something else...</option>
<option value="something 1">A thing</option>
<option value="something 2">A second thing</option>
<option value="something 3">Something else</option>
<option value="something 4">Another thing</option>
</select>
</form>
</div>
It seems more likely that you want the image rotation to start when the user selects an option then show the next select, if so this'll get you there:
$(document).ready(function(){
var header = $('body');
var current = 0;
// I did this with 4 images for testing, add as many as you like in yours
var backgrounds = ['url(http://stylonica.com/wp-content/uploads/2014/03/Nature___Seasons___Spring__038259_.jpg)'
, 'url(http://hd.wallpaperswide.com/thumbs/summer_holiday-t2.jpg)'
, 'url(http://www.grandfather.com/wp-content/uploads/2012/08/fall-road.jpg)'
, 'url(http://hooptricks.org/wp-content/uploads/2014/01/road-winter.jpg)'];
function SelectElement(valueToSelect)
{
var element = document.getElementById('test');
element.value = '1';
}
$('#test').change(function() {
// set the first image to the background
header.css('background-image', backgrounds[0]);
//start the timer
setInterval(nextBackground, 6000);
//hide the first select and show the second
$('#fisrtSelDiv').hide();
$('#secondSelDiv').show();
});
function nextBackground() {
current++;
current = current % backgrounds.length;
header.css('background-image', backgrounds[current]);
}
});
#secondSelDiv{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="black">
<div style="margin-top:22%;margin-bottom:-22%;">
<div id="fisrtSelDiv">
<form name="test">
<select id="test" name="test">
<option value="" selected="selected" disabled="disabled">Select Season..</option>
<option value="Season 1">Season 1</option>
<option value="Season 2">Season 2</option>
<option value="Season 3">Season 3</option>
<option value="Season 4">Season 4</option>
</select>
</form>
</div>
<div id="secondSelDiv">
<form name="test2">
<select id="test2" name="test">
<option value="" selected="selected" disabled="disabled">Select something else...</option>
<option value="something 1">A thing</option>
<option value="something 2">A second thing</option>
<option value="something 3">Something else</option>
<option value="something 4">Another thing</option>
</select>
</form>
</div>

Change the contents of select box based on another select box using javascript

How to change the contents of 2nd select box based on value of first select box. no jQuery but only JavaScript enable second select box based on various inputs from 1st select box(div2) only JavaScript no jQuery no inner HTML if switch used.
<script> //javascript
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("details").getElementsByTagName('div');
disO = document.getElementById("details").getElementsByTagName('di');
}
</script>
<div id="div2"> //select boxes
<select size="1" id="rambo" name="comm-name" selected="selected" onchange="showhide(this)" >
<option value="" selected="selected">-Select Office-</option>
<option value="3">HEAD OFFICE</option><option value="4">REGIONAL OFFICE</option>
<option value="5">DIVISIONAL OFFICE</option><option value="6">BRANCH OFFICE</option>
<option value="7">SERVICE CENTER</option><option value="8">EXTENSION COUNTER</option>
<option value="9">Show div 9</option><option value="10">Show div 10</option>
<option value="11">Show div 11</option><option value="12">Show div 12</option>
<option value="13">Show div 13</option><option value="14">Show div 14</option>
<option value="15">Show div 15</option><option value="16">Show div 16</option>
<option value="17">Show div 17</option><option value="17">Show div 18</option>
<option value="19">Show div 19</option><option value="18">Show div 20</option>
<option value="21">Show div 21</option>
</select>
</div>
<div id="di21"> <select name="" >
<option value="">Select an option</option>
<option value="4">Show div 4</option>
<option value="5">Show div 5</option>
<option value="6">Show div 6</option>
</select>This </div>
..... so on
//And this is asking me time and again to add some context to explain the code.. I do not know what to do ?
// the JavaScript function above opens up a new select box each time I change the option in the first select box.
Here is the Fidle
I simplified your html just for testing purpose and in function SetSel(elem) you can always write custom code to select second combo value as per logic

Categories