Various selects in form controlled by one main select - javascript

I want to update my dropdowns based on the main dropdown menu via javascript.
Consider this: there is a main select menu (dropdown) with months, from january to december, and we have 3 other blocks, but in those blocks there is month select, but, in this case they should be selected with the same month that was selected in the main selection. I don't know if I'm clear. If I change the main select, it should be reflected on the other 3.
I don't understand how to begin, because I can put some "onChange" event in the main select to call a javascript function, but I don't know how this javascript code can change the values of the other 3 selects of years in the other 3 blocks of the webpage.
I'm writing from my cellphone because I'm in a train so sadly I don't have any code to share with you, because I just only could make work the "OnChange" event.
Please suggest some solution. Thanks in advance.

You have the correct start.
By listening the changes from the Main selection, get the corresponding field from data to create new options for the child selection.
Here is an example. Hope can help.
let data ={
opt1 : {
child1 : ["opt1-child1-1","opt1-child1-2"],
child2 : ["opt1-child2-1","opt1-child1-2"],
child3 : ["opt1-child3-1","opt1-child1-2"],
},
opt2 : {
child1 : ["opt2-child1-1","opt2-child1-2"],
child2 : ["opt2-child2-1","opt2-child1-2"],
child3 : ["opt2-child3-1","opt2-child1-2"],
}
};
$("#main").on('change',function(){
let main = $(this).val();
console.log(main);
//set child1
$("#child1").html(""); //clean
data[main].child1.forEach(ele => {
$("#child1").append(`<option value="${ele}">${ele}</option>`);
});
//set child2
$("#child2").html(""); //clean
data[main].child2.forEach(ele => {
$("#child2").append(`<option value="${ele}">${ele}</option>`);
});
//set child3
$("#child3").html(""); //clean
data[main].child3.forEach(ele => {
$("#child3").append(`<option value="${ele}">${ele}</option>`);
});
});
<div>
<select id="main">
<option disabled selected>---Pick one---</option>
<option value="opt1">opt1</option>
<option value="opt2">opt2</option>
</select>
</div>
<select id="child1">
<option disabled selected>---choose main first---</option>
</select>
<select id="child2">
<option disabled selected>---choose main first---</option>
</select>
<select id="child3">
<option disabled selected>---choose main first---</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

How to click a dropdown menu and select option?

I have the following code
<select class="needsclick" id="country" name="order[country]">
<option value="USA" selected="selected">USA</option>
<option value="CANADA">CANADA</option>
</select>
I could do the following javascript command to change the option value
document.getElementById("country").value = 'CANADA'
however, this does not change the selected value and does not change the state box to province.
When I physically click this dropdown menu and change to CANADA, the effects of the change take place (the state box changes to province)
I am using Swift iOS to parse HTML and wondering what line of javascript code is needed to click a option value rather than changing the option value?
If I do the following after changing the value
document.getElementById("country").click()
it just clicks the menu but still does not change the state box to province (happens when physically clicking the option value)
How can I achieve this using a javascript command like the two above?
The state/province box is irrelevant to the code just relevant to the fact it changes when the dropdown is physically clicked and not when programmatically changed.
I can do the following code but it still does not change the state box to province (only if physically clicked)
document.getElementById("country")[1].selected = true
To work with the option elements within a select, you must access the options node list and then select one to work with.
Setting the value is separate from setting the selected flag.
var countries = document.getElementById("country");
var states = document.getElementById("provincesUSA");
var territories = document.getElementById("provincesCanada");
countries.addEventListener("change", function(e) { update(e); });
function update(e){
// show the correct sub-list based on the selected option
var country = countries[countries.selectedIndex];
if(country.value === "USA"){
states.classList.remove("hidden");
territories.classList.add("hidden");
} else if(country.value === "CANADA") {
territories.classList.remove("hidden");
states.classList.add("hidden");
} else {
territories.classList.add("hidden");
states.classList.add("hidden");
}
}
// To dynamically choose
document.querySelector("button").addEventListener("click", function(){
countries.options[2].selected = "selected"; // Canada
// Simulate the change event
update(countries);
});
#provincesUSA.hidden, #provincesCanada.hidden { display:none; }
<select class="needsclick" id="country" name="order[country]">
<option value="" selected="selected">Choose A Country</option>
<option value="USA">USA</option>
<option value="CANADA">CANADA</option>
</select>
<select id="provincesUSA" class="hidden" name="states">
<option value="al">Alabama</option>
<option value="ar">Arkansas</option>
</select>
<select id="provincesCanada" class="hidden" name="territories">
<option value="on">Ontario</option>
<option value="qu">Quebec</option>
</select>
<button>Force A Selection (click me whe CANADA is NOT selected)</button>
document.getElementById("country").selectedIndex = 2;

Adding arguments in url to choose values in multiple drop downs on page using javascript/jquery

I am trying to create a webpage where the content changes depending on which drop down options the user has selected. Once the user has made his first choice, the content of a drop down menu can be an additional nested drop down menu with another choice the user must make.
I am now trying to figure out how I can pre-select options by passing parameters in the URL for both the first drop down and a number of nestet drop downs.
I have the basic functionality down. Here's my HTML:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="js_select.js"></script>
<script type="text/javascript" src="js_drop.js"></script>
<link rel="stylesheet" type="text/css" href="css.css">
<select id="select" class="div-toggle" data-target=".my-info-1">
<option id="one" value="noselection" data-show=".noselection">
Choose option
</option>
<option id="two" value="2015" data-show=".2015">
2015
</option>
<option id="three" value="2014" data-show=".2014">
2014
</option>
</select>
<div class="my-info-1">
<div class="noselection hide">
No choice made
</div>
<div class="2015 hide">
2015
</div>
<div class="2014 hide">
A nested drop down within the 2014 selection:<br><br>
<select id="select" class="div-toggle" data-target=".my-info-2">
<option id="one" value="noselection2" data-show=".noselection2">
Choose option
</option>
<option id="two" value="s1" data-show=".s1">
January
</option>
<option id="three" value="s2" data-show=".s2">
February
</option>
</select>
<div class="my-info-2">
<div class="noselection2 hide">
No choice made
</div>
<div class="s1 hide">
Information about January
</div>
<div class="s2 hide">
Information about February
</div>
</div>
</div>
</div>
Here's my css.css:
.hide {
display: none;
}
And here's js_drop.js that makes content appear depending on the user selection. I found the script here: Change the content of a div based on selection from dropdown menu:
$(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');
});
I am now adding functionality to make it possible to link to a specific drop down selection and any nested selections by adding parameters to the URL, like in:
http://example.com/page.html?select=three&selectnested=two
I am using js_select.js for this function. I found the code here: How to create a hyperlink that directs to a page with pre-selected option in a drop-down menu?
$(document).ready(function() {
var select = GetUrlParameter("select");
$("#" + select).attr("selected", "");
});
function GetUrlParameter(name) {
var value;
$.each(window.location.search.slice(1).split("&"), function (i, kvp) {
var values = kvp.split("=");
if (name === values[0]) {
value = values[1] ? values[1] : values[0];
return false;
}
});
return value;
}
My guess at a solution would be to:
Change id on my second <select> to id="selectnested"
Add the following code to my js_select.js above the function
The code:
$(document).ready(function() {
var select = GetUrlParameter("selectnested");
$("#" + select).attr("selected", "");
});
But this solution does not choose a selection with-in the nested drop down when the page loads using my example URL above.
Any hint on solving this would be much appreciated.
The issue is that you have multiple elements with the same ID (both <select>s have the ID "select", the <option>s have repeated IDs "one", "two" and "three").
Change the IDs of the <select> and <option> elements so they don't conflict with each other.
Example:
<select id="select" class="div-toggle" data-target=".my-info-1">
<option id="select-one" value="noselection" data-show=".noselection">
Choose option
</option>
<option id="select-two" value="2015" data-show=".2015">
2015
</option>
<option id="select-three" value="2014" data-show=".2014">
2014
</option>
</select>
...
<select id="nested" class="div-toggle" data-target=".my-info-2">
<option id="nested-one" value="noselection2" data-show=".noselection2">
Choose option
</option>
<option id="nested-two" value="s1" data-show=".s1">
January
</option>
<option id="nested-three" value="s2" data-show=".s2">
February
</option>
</select>
This way, in your initialization function, you can do:
$(document).ready(function() {
// First selection menu options
var select = GetUrlParameter("select");
$("#select-" + select).attr("selected", "");
// "Nested" selection menu options
var select = GetUrlParameter("selectnested");
$("#nested-" + select).attr("selected", "");
});
And due to those prefixes (select- and nested-) jQuery will only find one element with that ID, and you'll hopefully have no more trouble!

Meteor reactive-var update one select element based on choice in other select element

I have two different select elements in a form
When I select an option in the first list, I want a corresponding option to be automatically set in the second list. I have made a few attempts, and I am close to getting it working using reactive-var but I need some help.
My template looks like this
<template name="inputForm">
<div class="section">
<form action="#">
<div class="row">
<div class="input-field col m4">
<select id="list-one">
<option value="" disabled selected>Choose your option</option>
<option value="1">100</option>
<option value="2">75</option>
<option value="3">50</option>
<option value="4">25</option>
<option value="5">25</option>
</select>
<label>Select List 1</label>
</div>
{{{secondListVar}}}
</div>
</form>
</div>
</template>
Then in the template helper file I have
var secondListVar = new ReactiveVar("<div class='input-field col m4'><select id='list-two'><option value='' selected>Choose your option</option></select><label>Select List 2</label></div>");
Template.inputForm.helpers({
secondListVar: function() {
return secondListVar.get();
}
});
Template.inputForm.events({
'change #list-one' : function() {
var listOneChoice = $('#list-one option:selected').text();
switch (listOneChoice) {
case "100":
secondListVar.set("<div class='input-field col m4'><select id='list-two'><option value='' selected>1.5</option></select><label>Select List 2</label></div>");
break;
case "75":
break;
case "50":
break;
case "25":
break;
case "25":
break;
}
}
});
If I select an option from the 1st list, the 2nd list seems to get cleared
but then if I click a radio button that causes the template to be hidden/shown I get this
So I have two issues
The rendering doesn't seem to be dynamic, in that I need to manually force it
When I get the 2nd list option shown, the corresponding state of the 1st list is lost
I would suggest creating the second list as html, and set its selection inside an autorun if you want to use a ReactiveVar.
Here's a working example :
http://meteorpad.com/pad/JLkM8ftKQuKhBvF3r/Lists
<template name="Main">
<label>Select List 1</label>
<select id="list-one">
<option value="" disabled selected>Choose your option</option>
<option value="1">100</option>
<option value="2">75</option>
<option value="3">50</option>
<option value="4">25</option>
<option value="5">25</option>
</select>
<label>Select List 2</label>
<select id="list-two">
<option value="" disabled selected>Choose your option</option>
<option value="1">100</option>
<option value="2">75</option>
<option value="3">50</option>
<option value="4">25</option>
<option value="5">25</option>
</select>
</template>
var SelectedItem = new ReactiveVar();
Template.Main.events({
'change #list-one' : function() {
var selected = $('#list-one option:selected').val();
SelectedItem.set(selected);
}
});
Template.Main.onCreated(function(){
this.autorun(function(){
var selected = SelectedItem.get();
$('#list-two option').eq(selected).prop('selected', true);
});
})
However, you may not even need a ReactiveVar, in this case you can set the second list directly via jquery if you wanted.
#looshi answer is the correct one, but I was also encountering issues due to the materialize package which are now sorted in my meteorpad example in light of the workaround posted here
I'm having a similar problem using Materialize. Your form select dropdowns are being created by Materialize based on values when the page is originally rendered. You will need to rerun the initialization code each time:
$('select').material_select();
Here's an example based on taking values from iron routers data function:
Tracker.autorun(function(e){
var data = Router.current().data();
Tracker.afterFlush(function(){
//dom is now created.
$('select').material_select();
});
});

Form select not saving in localStorage

I'm working on an HTML view for iAd Producer. I'm trying to add a list of sentences which have alternative words students can choose and to save those values to localStorage as they change and repopulate the selects with those values when the page is revisited.
I'm adapting some code I wrote which works fine to save multiple input boxes on a page. But I have strange behaviour when trying to use it with multiple selects. Basically, no matter which order the answers are completed in, only the last chosen value is being stored. When the page is revisited, the code attempts to put that value in each select. This, of course, fails for the two selects which do not have corresponding values.
I cannot see why this is happening and hope someone can spot the obvious. Thanks.
<div>
<script type="text/javascript">
var uniqueId = "FC2-U2-A-P29";
$(document).ready(function () {
function onStartup() {
$.each( $("select"), function() {
if (localStorage[$(this).attr("value")+uniqueId]) {
$(this).val(localStorage[$(this).attr("value")+uniqueId]);
}
});
}
onStartup();
});
$('.drop').change(function () {
localStorage[$(this).attr("value")+uniqueId] = $(this).val();
});
</script>
<form>
<label class="number">1.</label>
<label class="text">Breakfast is the </label>
<select name="select1" class="drop">
<option value="blank">Choose a word</option>
<option value="one1">one</option>
<option value="first1">first</option>
</select>
<label class="text"> meal of the day.</label>
<br>
<label class="number">2.</label>
<label class="text">I always eat </label>
<select name="select2" class="drop">
<option value="blank">Choose a word</option>
<option value="three2">three</option>
<option value="third2">third</option>
</select>
<label class="text"> meals a day.</label>
<br>
<label class="number">3.</label>
<label name="select3" class="text">My football team is in</label>
<select class="drop">
<option value="blank">Choose a word</option>
<option value="two3">two</option>
<option value="second3">second</option>
</select>
<label class="text"> place in the league.</label>
<br>
<button class="clearButton" onclick="clearAnswers()">Clear </button>
<script type="text/javascript">
function clearAnswers() {
$.each( $("select"), function() {
if (localStorage[$(this).attr("value")+uniqueId]) {
localStorage.removeItem($(this).attr("value")+uniqueId);
$(this).val("blank");
}
location.reload();
});
}
</script>
</form>
</div>
The probable reason for which this code fails in select is because of the following :
$.each( $("select"), function() {
if (localStorage[$(this).attr("value")+uniqueId]) { //select doesn't have any attribute value.
$(this).val(localStorage[$(this).attr("value")+uniqueId]);
}
});
Select tag doesn't have any value attribute. I think .val() is what you need here. If you look at the code, you are basically iterating on select tag and checking value attribute(which doesn't exist) of select. Try changing it to .val() and then try.
To save and load stuff from localstorage use:
localStorage.setItem(<key>, <value>);
and
localStorage.getItem(<key>);
There are multiple problems with your code.
The first one is that you should use .val() instead of .attr('value').
The second one is that the code to add the values in localStorage is executed before the DOM is created fully, so the selects dont exist yet. To overcome this you need to bind the change event on document.ready ( aka $(function() { }); ).
I've made a pastebin with the modified code: http://jsbin.com/jubijuyatu/2/
Your selector is invalid.
Change $(this).attr("value")+uniqueId with $("option:selected",this ).text()+uniqueId; in all occurrences.

Showing and hiding a selection when clicking on another selection on Javascript [duplicate]

This question already has answers here:
jQuery show/hide a div based on select value
(7 answers)
Closed 8 years ago.
In a nutshell, only show the selection #letters when option letters is selected, selection #numbers comes out when option numbers is selected, #letters disappears and #numbers is enabled?
Any help would be much appreciated. Thanks!
This is visible at the beginning:
<select id="test">
<option value="letters">letters</option>
<option value="numbers">numbers</option>
</select>
After clicking letters shows or enable #letters and show #numbers when numbers is selected:
<select id="letters">
<option value="a">A</option>
<option value="b">B</option>
</select>
<select id="numbers">
<option value="1">1</option>
<option value="2">2</option>
</select>
I would suggest that you use jQuery (more information) and try the following code:
// bind all events AFTER the page is loaded
$(document).ready(function () {
$('#test').change(function () { // every time the user selects an option in your test <select>
$('.yourSelect').hide(); // hide all <select>s with the class yourSelect
$('#'+$(this).val()).show(); // show the <select> with the id selected in test
});
});
Working Fiddle: http://jsfiddle.net/myx7S/1/
This is as simple as it gets - http://jsfiddle.net/yrshaikh/CBDaS/
function doSomething(){
var selection = document.getElementById('test').value
if(selection == "numbers") {
document.getElementById('letters').className = 'hide';
document.getElementById('numbers').className = '';
}
else {
document.getElementById('letters').className = '';
document.getElementById('numbers').className = 'hide';
}
}
and ofcourse, where .hide is a css class:
.hide {
display:none;
}
If I get it well, you want to create a dependent select box? If you select a first option, then you have more options coming.
I think this tutorial could help. It's made with jQuery. Pretty neat.

Categories

Resources