I'm brand new to JavaScript, so please be patient. I've searched online the last few days looking for a solution, but I'm not finding one. A big reason for that is I don't really know what I'm supposed to be looking for.
With that being said, help with code would be great. If you don't care to write any code in response, but would be willing to point me in the right direction as to what would be a solution for my problem, that would be fantastic as well.
What I'm trying to do: User chooses an option from the second dropdown box which then displays the 'SHOW ME WHERE TO GO' button. When the button is clicked, a div is displayed over the top with a video embedded in it to provide them directions.
My problem: I feel like I need an array or object of some kind to link select options to snippets of embed code for dropping into the directions_container div. I don't know how to link options selected by the user to the appropriate code snippets. Clicking the SHOW ME WHERE TO GO button should trigger the appropriate snippet of code to be inserted into the div tag.
Below is my current project code.
HTML
<div id="directions_container">
<p id="embed"></p>
<br>
<br>
<span href="" onclick="close_div()">Choose New Directions</span>
</div>
<div id="SelectionBoxes">
<select id="TransactionType" onchange="check();">
<option selected="selected" value="">I am a...</option>
<option value="DH">Drop and Hook</option>
<option value="Live">Live Unload</option>
<option value="LTL">LTL</option>
<option value="FedEx">FedEx Ground/Express</option>
<option value="Visitor">Visitor</option>
</select>
<br>
<br>
<select id="DHOps" style=display:none; onchange="showbtn();">
<option selected="selected" value="">Describe your transaction...</option>
<option value="LILO">Load In - Load Out</option>
<option value="LIEO">Load In - Empty Out</option>
<option value="EILO">Empty In - Load Out</option>
<option value="EIEO">Empty In - Empty Out</option>
<option value="BILO">Bobtail In - Load Out</option>
<option value="PUP">Pup Trailers/Containers</option>
<option value="CONT">Containers</option>
</select>
<select id="LUOps" style=display:none; onchange="showbtn();">
<option selected="selected" value="">Where will you be unloaded?</option>
<option value="WH1">Warehouse 1 / 100 Level Docks</option>
<option value="WH2">Warehouse 2 / 200 Level Docks</option>
<option value="WH3">Warehouse 3 / 300 Level Docks</option>
<option value="WH4">Warehouse 4 / 400 Level Docks</option>
</select>
<select id="LTLOps" style=display:none; onchange="showbtn();">
<option selected="selected" value="">Where do I go?</option>
<option value="327">Dock Door 327</option>
</select>
<select id="FEDEXOps" style=display:none; onchange="showbtn();">
<option selected="selected" value="">Describe your transaction...</option>
<option value="RETURNS">Returns Load In - Load Out</option>
<option value="EMPTY">Empty In - Load Out</option>
</select>
<select id="VISITOROps" style=display:none; onchange="showbtn();">
<option selected="selected" value="">What is the purpose of your visit?</option>
<option value="MAINT">Delivery for Maintenance</option>
<option value="VEND">Canteen/Vending</option>
<option value="GARBAGE">Garbage Pickup</option>
<option value="OFFICE">Visit Transportation Office</option>
</select>
<br>
<br>
<button id="submit" type="button" style=display:none; onclick="provideDirections();">SHOW ME WHERE TO GO</button>
</div>
CSS
#directions_container {
z-index: 1;
background-color: #FFFFFF;
display: none;
position: absolute;
width: 500px;
height: 300px;
}
JavaScript
function check() {
var dropdown = document.getElementById("TransactionType");
var current_value = dropdown.options[dropdown.selectedIndex].value;
if (current_value == "DH") {
document.getElementById("DHOps").style.display = "block";
document.getElementById("LUOps").style.display = "none";
document.getElementById("LTLOps").style.display = "none";
document.getElementById("FEDEXOps").style.display = "none";
document.getElementById("VISITOROps").style.display = "none";
document.getElementById("submit").style.display = "none";
}
if (current_value == "Live") {
document.getElementById("LUOps").style.display = "block";
document.getElementById("DHOps").style.display = "none";
document.getElementById("LTLOps").style.display = "none";
document.getElementById("FEDEXOps").style.display = "none";
document.getElementById("VISITOROps").style.display = "none";
document.getElementById("submit").style.display = "none";
}
if (current_value == "LTL") {
document.getElementById("LTLOps").style.display = "block";
document.getElementById("DHOps").style.display = "none";
document.getElementById("LUOps").style.display = "none";
document.getElementById("FEDEXOps").style.display = "none";
document.getElementById("VISITOROps").style.display = "none";
document.getElementById("submit").style.display = "none";
}
if (current_value == "FedEx") {
document.getElementById("FEDEXOps").style.display = "block";
document.getElementById("DHOps").style.display = "none";
document.getElementById("LUOps").style.display = "none";
document.getElementById("LTLOps").style.display = "none";
document.getElementById("VISITOROps").style.display = "none";
document.getElementById("submit").style.display = "none";
}
if (current_value == "Visitor") {
document.getElementById("VISITOROps").style.display = "block";
document.getElementById("DHOps").style.display = "none";
document.getElementById("LUOps").style.display = "none";
document.getElementById("LTLOps").style.display = "none";
document.getElementById("FEDEXOps").style.display = "none";
document.getElementById("submit").style.display = "none";
}
}
function showbtn() {
var childboxes = [
document.getElementById("DHOps"),
document.getElementById("LUOps"),
document.getElementById("LTLOps"),
document.getElementById("FEDEXOps"),
document.getElementById("VISITOROps"),
];
childboxes.forEach((childbox) => {
if (childbox.onchange) {
document.getElementById("submit").style.display = "block";
}
});
}
function provideDirections() {
var embed_directions = {}
document.getElementById("directions_container").style.display = "block";
}
function close_div () {
document.getElementById("directions_container").style.display = "none";
}
I think it would be a good idea to have the data about what to select in an array/object.
I guess there are a lot of new stuff here, but notice especially that the data item is inserted into the option element as itemdata. This is a trick for passing around data.
var data = [{
id: "1",
title: "Option 1",
suboptions: [{
id: "1a",
title: "Option 1a"
}, {
id: "1b",
title: "Option 1b"
}]
},
{
id: "2",
title: "Option 2",
suboptions: [{
id: "2a",
title: "Option 2a"
}, {
id: "2b",
title: "Option 2b"
}]
}
];
document.addEventListener('DOMContentLoaded', e => {
document.forms.selection.addEventListener('submit', e => {
e.preventDefault();
console.log(e.target.first.value,e.target.second.value, "was selected")
});
document.forms.selection.second.addEventListener('change', e => {
document.forms.selection.button.disabled = false;
});
document.forms.selection.first.addEventListener('change', e => {
let optVal = e.target.value;
let optElm = e.target.querySelector(`option[value = '${optVal}']`);
if (optElm){
update(optElm.itemdata.suboptions, document.forms.selection.second);
} else {
document.forms.selection.second.innderHTML = '';
document.forms.selection.second.disabled = true;
document.forms.selection.button.disabled = true;
}
});
update(data, document.forms.selection.first);
});
const update = (array, select) => {
select.innerHTML = '';
let opt = document.createElement('OPTION');
select.appendChild(opt);
array.forEach(item => {
let opt = document.createElement('OPTION');
opt.value = item.id;
opt.innerText = item.title;
opt.itemdata = item;
select.appendChild(opt);
});
select.disabled = false;
};
<form name="selection">
<select name="first" required disabled>
</select>
<select name="second" required disabled>
</select>
<button name="button" disabled>Go!</button>
</form>
Related
The purpose with the code is to let user choose a number from a dropdown-menu and show corresponding divs. The startpoint of divs is always that all are hidden. The "user-selected-number" should be used by Javascript to decide how many divs to show. In this case as following:
Dropdown-value: 1 = show balance 0
Dropdown-value: 2 = show balance 0,1
Dropdown-value: 3 = show balance 0,1,2
Dropdown-value: 4 = show balance 0,1,2,3
Observation:
I suspect the problem is that the javavascript picks up only the option that is predefined as "selected" which would mean it does never take the user-selected-value for further processing.
The var_dump of $_POST shows correct result/printout, everytime user selects an option from the dropdown menu.
Wanted behavour:
The user should on the frontend be able to pick a value in dropdown between 1-4 and the corrensponding divs (see list above) should be made visible.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Show divs based on dropdown</title>
<style>
.balance_0,
.balance_1,
.balance_2,
.balance_3
{
display: none;
}
</style>
</head>
<body>
<!-- Form (Years-selector) -->
<form class="year-selector" method="post">
<select class="dropdown_result" id="dropdown_result" name="selection">
<option value="" selected="selected" hidden="hidden">Select amount of years to report...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<button type="submit" name="button">Send</button>
</form>
<!-- Divs -->
<div class="balance_0">Balance-0</div>
<div class="balance_1">Balance-1</div>
<div class="balance_2">Balance-2</div>
<div class="balance_3">Balance-3</div>
<pre>
<?php var_dump($_POST); ?>
<script>
// Extract selected dropdown menu option.
var amountOfBalanceColumnsToShow =
document.getElementById("dropdown_result").selectedOptions[0].value;
// Show amount of balance divs based on above form.
if (amountOfBalanceColumnsToShow == 1) {
var x = document.getElementById("balance_0");
x.style.display = "block";
}
else if (amountOfBalanceColumnsToShow == 2) {
for (var i = 0; i <= 1; i++) {
var x = document.getElementById("balance_" + i);
x.style.display = "block";
}
}
else if (amountOfBalanceColumnsToShow == 3) {
for (var i = 0; i <= 2; i++) {
var x = document.getElementById("balance_" + i);
x.style.display = "block";
}
}
else if (amountOfBalanceColumnsToShow == 4) {
for (var i = 0; i <= 3; i++) {
var x = document.getElementById("balance_" + i);
x.style.display = "block";
}
}
</script>
</body>
</html>
Added event.preventDefault so the form does not actually submit and refresh the page removing the client side event. Added a click event to the button and ran conditionals that sets the style attributes to block for the numbers selected.
I assume you want to show each numbers corresponding amount of their divs, so if 3 is selected show balance_0, balance_1, balance_2 correct?
let e = document.querySelector('#dropdown_result');
let send = document.querySelector('#button');
let one = document.querySelector('.balance_0');
let two = document.querySelector('.balance_1');
let three = document.querySelector('.balance_2');
let four = document.querySelector('.balance_3');
let selected;
send.addEventListener('click', event => {
selected = Number(e.options[e.selectedIndex].value);
if(selected === 1){
one.style.display = "block";
two.style.display = "none";
three.style.display = "none";
four.style.display = "none";
}else if(selected === 2){
one.style.display = "block";
two.style.display = "block";
three.style.display = "none";
four.style.display = "none";
}else if(selected === 3){
one.style.display = "bloc";
two.style.display = "block";
three.style.display = "block";
four.style.display = "none";
}else if(selected === 4){
one.style.display = "block";
two.style.display = "block";
three.style.display = "block";
four.style.display = "block";
}
event.preventDefault();
});
.balance_0,
.balance_1,
.balance_2,
.balance_3
{
display: none;
}
<form class="year-selector" method="post">
<select class="dropdown_result" id="dropdown_result" name="selection">
<option value="" selected="selected">Select amount of years to report...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<button type="submit" id="button" name="button">Send</button>
</form>
<!-- Divs -->
<div class="balance_0">Balance-0</div>
<div class="balance_1">Balance-1</div>
<div class="balance_2">Balance-2</div>
<div class="balance_3">Balance-3</div>
There are several things you should consider in your code.
You are using button with type="submit" which causes to pages get reload each time and run the same script, so the value of amountOfBalanceColumnsToShow will always be the same (which is in your case it is your first option in the dropdown).
You are always just showing the blocks in each particular condition and don't get any consideration of hiding unnecessary ones.
You are getting element by its id where the balance div's have classes instead of id's.
To fix these things, you should first add an event listener to your submit button and prevent its default action, then get all the elements with balance class and after that with your conditions iterate through them and specify which one has to be shown and which one has to hidden.
So your final code should be something like this:
// Extract selected dropdown menu option.
var element = document.getElementById("dropdown_result");
var submitButton = document.querySelector('button[type="submit"]');
var balanceDivs = document.querySelectorAll("[class*='balance']");
var balanceDivsLength = balanceDivs.length;
submitButton.addEventListener("click", function(event) {
event.preventDefault();
var amountOfBalanceColumnsToShow =
element.options[element.selectedIndex].value;
// Show amount of balance divs based on above form.
if (amountOfBalanceColumnsToShow == 1) {
for (var i = 0; i < balanceDivsLength; i++) {
if (balanceDivs[i].classList.contains("balance_0")) {
balanceDivs[i].style.display = "block";
} else {
balanceDivs[i].style.display = "none";
}
}
} else if (amountOfBalanceColumnsToShow == 2) {
for (var i = 0; i < balanceDivsLength; i++) {
if (
balanceDivs[i].classList.contains("balance_0") ||
balanceDivs[i].classList.contains("balance_1")
) {
balanceDivs[i].style.display = "block";
} else {
balanceDivs[i].style.display = "none";
}
}
} else if (amountOfBalanceColumnsToShow == 3) {
for (var i = 0; i < balanceDivsLength; i++) {
if (!balanceDivs[i].classList.contains("balance_3")) {
balanceDivs[i].style.display = "block";
} else {
balanceDivs[i].style.display = "none";
}
}
} else if (amountOfBalanceColumnsToShow == 4) {
for (var i = 0; i < balanceDivsLength; i++) {
balanceDivs[i].style.display = "block";
}
}
});
.balance_0,
.balance_1,
.balance_2,
.balance_3 {
display: none;
}
<!-- Form (Years-selector) -->
<form class="year-selector" method="post">
<select class="dropdown_result" id="dropdown_result" name="selection">
<option value="" selected="selected" hidden="hidden">Select amount of years to report...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<button type="submit" name="button">Send</button>
</form>
<!-- Divs -->
<div class="balance_0">Balance-0</div>
<div class="balance_1">Balance-1</div>
<div class="balance_2">Balance-2</div>
<div class="balance_3">Balance-3</div>
I'm new to jquery, and i wanted to convert my javascript code that includes two select tags one main and the other for sub, clicking a different option in the main will display a different sub select tag because all of my select tags display are set to none, but i dont know how to structure a jquery
here's my HTML for my select tag
<select name="category" id="c_type" onchange="selectChoice()">
<option value=""></option>
<option value="Learning Environment">Learning Environment</option>
<option value="Learning Support">Learning Support</option>
<option value="Technology Support">Technology Support</option>
<option value="Wellness">Wellness, Health, and Nutrition</option>
<option value="Training">Training and Skills Development</option>
<option value="Financial">Financial Support and Subsidy</option>
<option value="Assistive">Assistive Learning Devices for Students with Special Needs</option>
</select>
<select name="specifics1" id="LE" style="display:none">
<option value=""></option>
<option value="Classroom">Classroom</option>
<option value="Laboratory Room">Laboratory Room</option>
</select>
<select name="specifics2" id="LS" style="display:none">
<option value=""></option>
<option value="Lab Equipments">Lab Equipments</option>
<option value="School Supplies">School Supplies</option>
</select>
<select name="specifics3" id="TS" style="display:none">
<option value=""></option>
<option value="Computer Units">Computer Units</option>
<option value="Internet">Internet Connectivity</option>
</select>
<select name="specifics4" id="WT" style="display:none">
<option value=""></option">
<option value="Feeding">Feeding Program</option>
<option value="Medical Kits">Medical Kits</option>
</select>
<select name="specifics5" id="TAD" style="display:none">
<option value=""></option>
<option value="Pupil Training">Student/Pupil Training</option>
<option value="Literacy Training">Literacy Training</option>
</select>
<select name="specifics6" id="FIN" style="display:none">
<option value=""></option>
<option value="Fare">Fare</option>
<option value="Meals">Meals</option>
</select>
<select name="specifics7" id="ASL" style="display:none">
<option value=""></option>
<option value="Braile">Braile</option>
<option value="Hearing Aids">Hearing Aids</option>
</select>
finally here is my javascript
function selectChoice(){
var main = document.getElementById("c_type").value;
var s1 = document.getElementById("LE");
var s2 = document.getElementById("LS");
var s3 = document.getElementById("TS");
var s4 = document.getElementById("WT");
var s5 = document.getElementById("TAD");
var s6 = document.getElementById("FIN");
var s7 = document.getElementById("ASL");
if(main === "Learning Environment"){
s1.style.display = "block";
s2.style.display = "none";
s3.style.display = "none";
s4.style.display = "none";
s5.style.display = "none";
s6.style.display = "none";
s7.style.display = "none";
s1.required = true;
s2.required = false;
s3.required = false;
s4.required = false;
s5.required = false;
s6.required = false;
s7.required = false;
s1.selectedIndex = 0;
s2.selectedIndex = 0;
s3.selectedIndex = 0;
s4.selectedIndex = 0;
s5.selectedIndex = 0;
s6.selectedIndex = 0;
s7.selectedIndex = 0;
}else if(main === "Learning Support"){
s1.style.display = "none";
s2.style.display = "block";
s3.style.display = "none";
s4.style.display = "none";
s5.style.display = "none";
s6.style.display = "none";
s7.style.display = "none";
s1.required = false;
s2.required = true;
s3.required = false;
s4.required = false;
s5.required = false;
s6.required = false;
s7.required = false;
s1.selectedIndex = 0;
s2.selectedIndex = 0;
s3.selectedIndex = 0;
s4.selectedIndex = 0;
s5.selectedIndex = 0;
s6.selectedIndex = 0;
s7.selectedIndex = 0;
}else if(main === "Technology Support"){
s1.style.display = "none";
s2.style.display = "none";
s3.style.display = "block";
s4.style.display = "none";
s5.style.display = "none";
s6.style.display = "none";
s7.style.display = "none";
s1.required = false;
s2.required = false;
s3.required = true;
s4.required = false;
s5.required = false;
s6.required = false;
s7.required = false;
s1.selectedIndex = 0;
s2.selectedIndex = 0;
s3.selectedIndex = 0;
s4.selectedIndex = 0;
s5.selectedIndex = 0;
s6.selectedIndex = 0;
s7.selectedIndex = 0;
}}
Looking at it i have 7 sub select tags with different select names and ids so it will be probably long but its working, what i want is to shorten it using jquery but i don't know how,
IMHO here is the shortest way to write a similar code, and much easier to maintain
const Category = [
{ type:'Learning Environment', ref:'LE', specs: [ 'Classroom', 'Laboratory Room' ] }
, { type:'Learning Support', ref:'LS', specs: [ 'Lab Equipments', 'School Supplies' ] }
, { type:'Technology Support', ref:'TS', specs: [ 'Computer Units', 'Internet Connectivity' ] }
, { type:'Wellness, Health, and Nutrition', ref:'WT', specs: [ 'Feeding Program', 'Medical Kits' ] }
, { type:'Training and Skills Development', ref:'TAD', specs: [ 'Student/Pupil Training', 'Literacy Training' ] }
, { type:'Financial Support and Subsidy', ref:'FIN', specs: [ 'Fare', 'Meals' ] }
, { type:'Assistive Learning Devices for Students with Special Needs', ref:'ASL', specs: [ 'Braile', 'Hearing Aids' ] }
];
const Select_category = document.querySelector('#c_type')
, Select_specs = document.querySelector('#specs')
;
// first initialisation on load...
let item = 0;
Select_category[item++] = new Option('','');
for (let cat of Category)
{
Select_category[item++] = new Option(cat.type, cat.ref );
}
// ... end initialisation.
Select_category.onchange = function()
{
Select_specs.innerHTML = null;
if (Select_category.value === ''){
Select_specs.classList.add('noDisplay');
}
else
{
let item = 0;
Select_specs[item++] = new Option('','');
Category.find(cat=>cat.ref===Select_category.value).specs.forEach((spec,index)=>{
Select_specs[item++] = new Option(spec, index );
})
Select_specs.classList.remove('noDisplay');
}
}
.noDisplay { display: none; }
<select name="category" id="c_type" ></select>
<select name="specs" id="specs" class="noDisplay"></select>
I have two select element and I want to show some options in second select based on what user choose at first select.
consider first select have two options : a , b ...
if user choose 'a' from first select :
the second select optiones should be -> c , d ...
and if user choose 'b' from first select :
the second select optiones should be : e , f ...
I have done some coding but the problem is at the start when user doesnt choose any option from first select the second select is always empty(it should show c , d)
<!DOCTYPE html>
<html>
<body>
<select id="s1" required>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select id="s2" required > </select>
<script>
document.getElementById("s1").onchange = function() {
document.getElementById('s2').disabled = false; //enabling s2 select
document.getElementById('s2').innerHTML = ""; //clear s2 to avoid conflicts between options values
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
if (this.value == 'a') {
opt0.textContent = "c";
opt1.textContent = "d";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
} else if (this.value == 'b') {
opt0.textContent = "e";
opt1.textContent = "f";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
}
};
</script>
</body>
</html>
If you can save the option values in a lookup object (or JSON):
function setOptions(select, values) {
for (var i = select.length = values.length; i--; )
select[i].innerText = values[i]
}
function value(select) { return select.value || select[0].value } // 1st item by default
var data = { 1: { 1.1: [1.11, 1.12], 1.2: [1.21, 1.22] },
2: { 2.1: [2.11, 2.12], 2.2: [2.21, 2.22], 2.3: [2.31, 2.32, 2.33] } }
s2.onchange = function() { setOptions(s3, data[value(s1)][value(s2)]) }
s1.onchange = function() { setOptions(s2, Object.keys(data[value(s1)])); s2.onchange() }
setOptions(s1, Object.keys(data)); s1.onchange(); // fill the options
<select id=s1 required size=3></select>
<select id=s2 required size=3></select>
<select id=s3 required size=3></select>
This code is based on JavaScript (No need for jQuery)
change Id name and value (x=="desire_value") according to your code
function myFunction() {
var x = document.getElementById("select1").value;
if (x == "3") document.getElementById("select2").style.display = "block";
else document.getElementById("select2").style.display = "none";
}
<select id="select1" onchange="myFunction()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="select2" style="display: none;">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
You have to write the functionality outside of onchange(). Try the following:
document.getElementById("s1").onchange = function() {
document.getElementById('s2').disabled = false; //enabling s2 select
document.getElementById('s2').innerHTML = ""; //clear s2 to avoid conflicts between options values
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
if (this.value == 'a') {
opt0.textContent = "c";
opt1.textContent = "d";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
} else if (this.value == 'b') {
opt0.textContent = "e";
opt1.textContent = "f";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
}
};
let element = document.getElementById("s1");
let selOption = element.options[element.selectedIndex].value;
if(selOption == 'a'){
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
opt0.textContent = "c";
opt1.textContent = "d";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
}
<select id="s1" required>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select id="s2" required > </select>
Why don't you just put that hard coded...
<!DOCTYPE html>
<html>
<body>
<select id="s1" required>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select id="s2" required >
<option value="c">c</option>
<option value="d">d</option>
</select>
<script>
document.getElementById("s1").onchange = function() {
document.getElementById('s2').disabled = false; //enabling s2 select
document.getElementById('s2').innerHTML = ""; //clear s2 to avoid conflicts between options values
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
if (this.value == 'a') {
opt0.textContent = "c";
opt1.textContent = "d";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
} else if (this.value == 'b') {
opt0.textContent = "e";
opt1.textContent = "f";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
}
};
</script>
</body>
</html>
One approach to contemplate is populating the dependant dropdowns with all values and use a data attribute for the parent-child relationship. Javascript then clones and removes the options for later insertion.
The functional javascript is now very lean and the dependency relationships are maintained in the DOM.
var s2Clone;
// Doesn't work in older IEs
//CLone the Dependant drop down and hide
document.addEventListener('DOMContentLoaded', function(){
s2Clone = document.getElementById("s2").cloneNode(true);
document.getElementById("s2").innerHTML = "";
}, false);
document.getElementById("s1").onchange = function() {
var selected = this.value;
//Get the nodes with a parent attribute of the selected data
var optionsToInsert = s2Clone.querySelectorAll("[data-parent='" + selected +"']");
//clear existing
var s2 = document.getElementById("s2");
s2.innerHTML = "";
//Add The new options.
for(i = 0; i < optionsToInsert.length; i++)
{
s2.appendChild(optionsToInsert[i]);
}
}
<select id="s1" required>
<option value="">Please select</option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select id="s2" required >
<option value="a1" data-parent="a">a - 1</option>
<option value="a2" data-parent="a">a - 2</option>
<option value="a3" data-parent="a">a - 3</option>
<option value="b1" data-parent="b">b - 1</option>
<option value="b2" data-parent="b">b - 2</option>
<option value="b3" data-parent="b">b - 3</option>
</select>
This is my dropdown menu.
<select id="q-rank">
<option value="1">Rank 1</option>
<option value="2">Rank 2</option>
<option value="3">Rank 3</option>
<option value="4">Rank 4</option>
<option value="5">Rank 5</option>
</select>
The value in the span tags is what I want to change.
<span id="q-cd">16</span>
<span id="q-stats1">70</span>
This is my javascript.
var qSelect = document.getElementById("q-rank");
var qCD = document.getElementById("q-cd");
var qStats1 = document.getElementById("q-stats1");
if(qSelect.value == "1"){
qCD.innerHTML = "worked";
qStats1.innerHTML = "70";
}
if(qSelect.value == "2"){
qCD.innerHTML = "15";
qStats1.innerHTML = "115";
}
if(qSelect.value == "3"){
qCD.innerHTML = "14";
qStats1.innerHTML = "160";
}
Initially, when the page loads, the first if statement works. For example, if I change the innerHTML of the first if statement to something like "test", when I load the page, the values in the span tag is "test". However, by selecting "rank 2", it doesn't change the inner HTML of the span tags.
Preferably, I want to accomplish this using pure Javascript but Jquery is welcomed.
You code works fine, just you need to add eventListener, which calls changes every-time when you change dropdown value of select, as below.
var qSelect = document.getElementById("q-rank");
function clck(){
var qCD = document.getElementById("q-cd");
var qStats1 = document.getElementById("q-stats1");
if(qSelect.value == "1"){
qCD.innerHTML = "worked";
qStats1.innerHTML = "70";
}
if(qSelect.value == "2"){
qCD.innerHTML = "15";
qStats1.innerHTML = "115";
}
if(qSelect.value == "3"){
qCD.innerHTML = "14";
qStats1.innerHTML = "160";
}
}
qSelect.addEventListener('change',clck);
<select id="q-rank">
<option value="1">Rank 1</option>
<option value="2">Rank 2</option>
<option value="3">Rank 3</option>
<option value="4">Rank 4</option>
<option value="5">Rank 5</option>
</select>
<span id="q-cd">16</span>
<span id="q-stats1">70</span>
Put the if statements in a function, and call that function on the change event of the select.
<select id="q-rank" onchange="setStats()">
<option value="1">Rank 1</option>
<option value="2">Rank 2</option>
<option value="3">Rank 3</option>
<option value="4">Rank 4</option>
<option value="5">Rank 5</option>
</select>
Alternative solution with some form of a "dictionary":
(function(){
let qSelect = document.getElementById('q-rank');
let qCD = document.getElementById('q-cd');
let qStats1 = document.getElementById('q-stats1');
let values = {
1: { cd: 'worked', stat: '70' },
2: { cd: '15', stat: '115' },
some: { cd: '14', stat: '160' },
other: { cd: '42', stat: 'hello' },
key: { cd: 'hey', stat: 'hi' }
};
qSelect.addEventListener('change', e => {
let value = values[e.target.value];
qCD.innerHTML = value.cd;
qStats1.innerHTML = value.stat;
});
qSelect.dispatchEvent(new Event('change'));
})();
<select id="q-rank">
<option value="1">Rank 1</option>
<option value="2">Rank 2</option>
<option value="some">Rank 3</option>
<option value="other">Rank 4</option>
<option value="key">Rank 5</option>
</select>
<span id="q-cd"></span>
<span id="q-stats1"></span>
Just use addEventListener and put your logic inside the function in the javascript.
var qSelect = document.getElementById("q-rank");
var qCD = document.getElementById("q-cd");
var qStats1 = document.getElementById("q-stats1");
qSelect.addEventListener("change", changer, false)
function changer() {
if(qSelect.value == "1"){
qCD.innerHTML = "worked";
qStats1.innerHTML = "70";
}
if(qSelect.value == "2"){
qCD.innerHTML = "15";
qStats1.innerHTML = "115";
}
if(qSelect.value == "3"){
qCD.innerHTML = "14";
qStats1.innerHTML = "160";
}
}
}
I want to create 4 cascading dropdown list JavaScript i came i across this code online but want i want to add the last input on this code and the last input depend on citySelect. Please help i been searching and i only find three cascading dropdown
<form name="myform" id="myForm">
<select name="optone" id="stateSel" size="1">
<option value="" selected="selected">Select state</option>
</select>
<br>
<br>
<select name="opttwo" id="countySel" size="1">
<option value="" selected="selected">Please select state first</option>
</select>
<br>
<br>
<select name="optthree" id="citySel" size="1">
<option value="" selected="selected">Please select county first</option>
</select>
<br>
<br>
<select name="optfour" id="branchSel" size="1">
<option value="" selected="selected">Please select branch first</option>
</select>
</form>
<script>
var stateObject = {
"California": {
"Monterey": ["Salinas", "Gonzales"],
"Alameda": ["Oakland", "Berkeley"]
},
"Oregon": {
"Douglas": ["Roseburg", "Winston"],
"Jackson": ["Medford", "Jacksonville"]
}
}
window.onload = function () {
var stateSel = document.getElementById("stateSel"),
countySel = document.getElementById("countySel"),
citySel = document.getElementById("citySel");
for (var state in stateObject) {
stateSel.options[stateSel.options.length] = new Option(state, state);
}
stateSel.onchange = function () {
countySel.length = 1; // remove all options bar first
citySel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
for (var county in stateObject[this.value]) {
countySel.options[countySel.options.length] = new Option(county, county);
}
}
stateSel.onchange(); // reset in case page is reloaded
countySel.onchange = function () {
citySel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
var cities = stateObject[stateSel.value][this.value];
for (var i = 0; i < cities.length; i++) {
citySel.options[citySel.options.length] = new Option(cities[i], cities[i]);
}
}
}
</script>
I would go with an out of the box working solution. Much faster and easier to implement.
Such as : http://plugins.krajee.com/dependent-dropdown/demo
Hope this helps!