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";
}
}
}
Related
I added my html and js snippet however it still not completed. Sorry if the code is a bit messy this is my first attempt for me to build something like this on my own.
`
var selectBread = document.querySelectorAll(".bread-select");
var sauceSelect = document.querySelectorAll(".sauces-select");
var checkBoxes = document.getElementsByTagName("input");
var orderModal = document.getElementById("order-modal");
let chosenItem;
let chosenItemPrice;
var ingredients = [];
var ingredientsPrice = [];
let selectedItem;
var sideDishes = [];
var drink = [];
var toasted;
var currentSandwich = {};
var breadAndPrice = [
["baguette", 0.8],
["burger bun", 0.8],
["ciabatta", 0.9],
["focaccia", 1.5],
["ftira", 0.8],
["olive bread", 1.3],
["rye bread", 1.3],
["sliced bread", 0.9],
["tortilla", 1.6],
["wheat bread", 0.9],
["whole grain bread", 1.2]
];
var sauceAndPrice = [
["chili sauce", 0.25],
["garlic and olive oil", 0.35],
["ketchup", 0.15],
["mayonnaisee", 0.15],
["garlic basil mayo", 0.45],
["mustard", 0.25]
];
function getBreadInfo(el, currentOption) {
for (var i = 0; i < el.length; i++) {
//add event listener to all bread select menu options
el[i].addEventListener("change", function() {
selectedItem = event.target.value; //current selected item
getArrIndex(currentOption, selectedItem);
if (event.target.name === "bread-select") {
currentSandwich.breadType = chosenItem;
currentSandwich.breadPrice = chosenItemPrice;
} else if (event.target.name === "sauce-select") {
currentSandwich.sauce = chosenItem;
currentSandwich.saucePrice = chosenItemPrice;
} else if (event.target.name === "side-dishes-select") {
currentSandwich.sideDish = chosenItem;
currentSandwich.sideDishPrice = chosenItemPrice;
} else if (event.target.name === "drinks-select") {
currentSandwich.drinkSelect = chosenItem;
currentSandwich.drinkPrice = chosenItemPrice;
} else if (event.target.name === "toasted-select") {
currentSandwich.toasted = chosenItem;
}
});
}
}
function getArrIndex(arr, val) {
// val is the selected item
for (var i = 0; i < arr.length; i++) {
//iterate through the current choosen array
if (arr[i][0] === val) {
// when selected item is found in the array
chosenItem = arr[i][0]; // store the item in choosenItem value
chosenItemPrice = arr[i][1]; // store the item price in choosenItem value
}
}
}
getBreadInfo(selectBread, breadAndPrice);
getBreadInfo(sauceSelect, sauceAndPrice);
//get the index of the selected item from the bread and price array
function getIngredientsInfo() {
for (var i = 0; i < checkBoxes.length; i++) {
//loop check boxes
checkBoxes[i].addEventListener("change", function() {
//add event listener to check boxes
if (event.target.checked) {
//check if check boxes are checked
ingredients.push(event.target.name); //push the name of ingredient to ingredients array
ingredientsPrice.push(event.target.value); //get the price of the item checked from value attr and push it to ingredientsPrice array
} else if (event.target.checked === false) {
var index = ingredients.indexOf(event.target.name);
ingredients.splice(index, 1);
ingredientsPrice.splice(index, 1);
}
});
}
}
getIngredientsInfo();
<section class="order-section">
<h2 class="selection-header">Choose your...</h2>
<div class="select-container">
<select class="bread-select" name="bread-select">
<option selected disabled>Bread Type</option>
<option value="baguette">Baguette</option>
<option value="burger bun">Burger Bun</option>
<option value="ciabatta">Ciabatta</option>
<option value="focaccia">Focaccia</option>
<option value="ftira">Ftira</option>
<option value="olive bread">Olive Bread</option>
<option value="rye bread">Rye Bread</option>
<option value="sliced bread">Sliced Bread</option>
<option value="tortilla">Tortilla</option>
<option value="wheat bread">Wheat Bread</option>
<option value="whole grain bread">Whole Grain Bread</option>
</select>
<select class="sauces-select" name="sauce-select">
<option selected disabled>Sauces</option>
<option value="chili sauce">Chili Sauce</option>
<option value="garlic and olive oil">Garlic and Olive Oil</option>
<option value="ketchup">Ketchup</option>
<option value="mayonnaise">Mayonnaise</option>
<option value="garlic basil mayo">Garlic Basil Mayo</option>
<option value="mustard">Mustard</option>
</select>
<select class="side-dishes-select" name="side-dishes-select">
<option selected disabled>Side Dishes</option>
<option value="coleslaw">Coleslaw</option>
<option value="curly fries">Curly Fries</option>
<option value="mixed salad">Mixed Salad</option>
<option value="potato wedges">Potato Wedges</option>
<option value="potatoes salad">Potatoes Salad</option>
<option value="sliced Potatoes fries">Sliced Potatoes Fries</option>
<option value="sweet potatoes fries">Sweet Potatoes Fries</option>
</select>
<select class="drinks-select" name="drinks-select">
<option selected disabled>Drinks</option>
<option value="Still Water">Still Water</option>
<option value="Fizzy Water">Fizzy Water</option>
<option value="coca cola">Coca Cola</option>
<option value="sprite">Sprite</option>
<option value="fanta">Fanta</option>
<option value="kinnie">Kinnie</option>
<option value="cisk">Cisk</option>
</select>
<select class="toasted-select" name="toasted-select">
<option selected disabled>Toasted</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
</section>
`I have a function which I am using to get data from select menus and I would like to save the data to an object by passing it as an argument. At the moment the only solution I found is to use if statements but it look bad. Any help to refactor this please?
if (event.target.name === "bread-select") {
currentSandwich.breadType = chosenItem;
currentSandwich.breadPrice = chosenItemPrice;
} else if (event.target.name === "sauce-select") {
currentSandwich.sauce = chosenItem;
currentSandwich.saucePrice = chosenItemPrice;
} else if (event.target.name === "side-dishes-select") {
currentSandwich.sideDish = chosenItem;
currentSandwich.sideDishPrice = chosenItemPrice;
} else if (event.target.name === "drinks-select") {
currentSandwich.drinkSelect = chosenItem;
currentSandwich.drinkPrice = chosenItemPrice;
} else if (event.target.name === "toasted-select") {
currentSandwich.toasted = chosenItem;
}
I'd suggest the switch is the way to go, it is both faster and better practice.
switch(event.target.name) {
case 'bread-select':
currentSandwich.breadType = chosenItem;
currentSandwich.breadPrice = chosenItemPrice;
break;
...
default:
}
Thanks
You can use a string to make a property assignment to and object using [] bracket notation. So if you are able to get a relevant property name, or part of a property name from your selects, that should work for you.
var selects = document.querySelectorAll('select');
for(var i = 0; i < selects.length; i++){
selects[i].addEventListener('change', selectHandler);
}
var currentSandwich = {};
var prices = {
soda : .5,
tea : .5,
lemonade : 1,
water : 0,
corn : 2,
potatoes : 2.5,
carrots : 1.5
};
function selectHandler(evt){
var name = evt.target.name;
var selection = evt.target.value;
currentSandwich[name] = selection;
if(prices[selection]){
currentSandwich[name+"price"] = prices[selection];
}else{
currentSandwich[name+"price"] = 0;
}
console.log(currentSandwich);
}
<select name='drink'>
<option value=''>Please Choose One</option>
<option value='soda'>Soda</option>
<option value='tea'>Tea</option>
<option value='lemonade'>Lemonade</option>
<option value='water'>Water</option>
</select>
<select name='side'>
<option value=''>Please Choose One</option>
<option value='corn'>Corn</option>
<option value='potatoes'>Potatoes</option>
<option value='carrots'>Carrots</option>
</select>
This is a significantly different approach. It stores prices and some keys in the HTML markup, and uses a simple function to use these to update your sandwich.
I don't know if this sort of refactoring is what you were looking for, but it's one reasonable way to avoid such repetitive logic.
var sandwich = {};
var sandwichContainer = document.getElementById('sandwich-options');
sandwichContainer.addEventListener('change', function(ev) {
var select = event.target;
var choice = select.selectedOptions[0];
var choiceName = select.dataset.choiceName;
sandwich[choiceName] = choice.value
var priceName = select.dataset.choicePrice;
if (priceName) {
sandwich[priceName] = Number(choice.dataset.price);
}
console.log(sandwich)
});
<section class="order-section">
<h2 class="selection-header">Choose your...</h2>
<div id="sandwich-options">
<select class="bread-select" name="bread-select"
data-choice-name="breadType" data-choice-price="breadPrice">
<option selected disabled>Bread Type</option>
<option value="baguette" data-price="0.8">Baguette</option>
<option value="burger bun" data-price="0.8">Burger Bun</option>
<option value="ciabatta" data-price="0.9">Ciabatta</option>
<option value="focaccia" data-price="1.5">Focaccia</option>
<option value="ftira" data-price="0.8">Ftira</option>
<option value="olive bread" data-price="1.3">Olive Bread</option>
<option value="rye bread" data-price="1.3">Rye Bread</option>
<option value="sliced bread" data-price="0.9">Sliced Bread</option>
<option value="tortilla" data-price="1.6">Tortilla</option>
<option value="wheat bread" data-price="0.9">Wheat Bread</option>
<option value="whole grain bread" data-price="1.2">Whole Grain Bread</option>
</select>
<select class="sauces-select" name="sauce-select" data-
choice-name="sauce", data-choice-price="saucePrice">
<option selected disabled>Sauces</option>
<option value="chili sauce" data-price="0.25">Chili Sauce</option>
<option value="garlic and olive oil" data-price="0.35">Garlic and Olive Oil</option>
<option value="ketchup" data-price="0.15">Ketchup</option>
<option value="mayonnaise" data-price="0.15">Mayonnaise</option>
<option value="garlic basil mayo" data-price="0.45"
>Garlic Basil Mayo</option>
<option value="mustard" data-price="0.25">Mustard</option>
</select>
<select class="toasted-select" name="toasted-select" data-choice-name="toasted">
<option selected disabled>Toasted</option>
<option value="yes" data-price="0">Yes</option>
<option value="no" data-price="0">No</option>
</select>
</div>
</section>
An alternate approach would be to store all your prices in a object keyed by the select names, something like this:
var prices = {
'bread-select': {
'baguette': 0.8,
...
},
'sauces-select': {
'chili sauce': 0.25,
...
},
...
};
and then use select.name and choice.value from the above to key into this object. You would also need another object, or a way to enhance this one to store the final property names.
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>
Below are my codes which allows user to select multiple values from the drop down list and when the user clicks the button 'Go' the selected values will be displayed on the new page. I've also created classes for both attributes in order to list the selected values.
Unfortunately, when the button is clicked after selections, nothing is being displayed. Need help on this.
"mainTest.html" page.
< script type = "text/javascript" >
(function() {
/**
* Handles the click of the submit button.
*/
function onSubmitClicked(event) {
var url = 'newPageTest.html?';
var foodbevs = document.getElementsByClassName('foodbeverage');
for (var i = 0; i < foodbevs.length; i++) {
if (i > 0) url += '&';
url += 'foodbeverage=' + encodeURIComponent(foodbevs[i].value);
}
var statuses = document.getElementsByClassName('status');
for (i = 0; i < statuses.length; i++) {
url += '&status=' + encodeURIComponent(statuses[i].value);
}
location.href = url;
}
// Get the button from the DOM.
var submitButton = document.getElementById('btngo');
// Add an event listener for the click event.
submitButton.addEventListener('click', onSubmitClicked);
})();
<
/script>
<!DOCTYPE html>
<html>
<body>
<h4 style="color:darkblue">Choose Your Food/Beverage & Quantity : </h4>
<table>
<tr>
<td>
<B>Choose a Food/Beverage : </B>
<select class="foodbeverage">
<optgroup label="DEFAULT">
<option value = "NONE">NONE</option>
</optgroup>
<optgroup label="Food">
<option value = "Chicken Chop">Chicken Chop</option>
<option value = "Pasta">Pasta</option>
<option value = "Pizza">Pizza</option>
<option value = "Chocolate Cake">Chocolate Cake</option>
<option value = "Red Velvet Cake">Red Velvet Cake</option>
<option value = "Ice Cream Cake">Ice Cream Cake</option>
</optgroup>
<optgroup label="Beverages">
<option value = "Milk">Milk</option>
<option value = "Fresh Juice">Fresh Juice</option>
<option value = "Ice Cream">Ice Cream</option>
<option value = "Coffee">Coffee</option>
<option value = "Carbonated Can Drink">Carbonated Can Drink</option>
<option value = "Water">Water</option>
</optgroup>
</select>
<br/>
<B>Choose a Food/Beverage : </B>
<select class="foodbeverage">
<optgroup label="DEFAULT">
<option value = "NONE">NONE</option>
</optgroup>
<optgroup label="Food">
<option value = "Chicken Chop">Chicken Chop</option>
<option value = "Pasta">Pasta</option>
<option value = "Pizza">Pizza</option>
<option value = "Chocolate Cake">Chocolate Cake</option>
<option value = "Red Velvet Cake">Red Velvet Cake</option>
<option value = "Ice Cream Cake">Ice Cream Cake</option>
</optgroup>
<optgroup label="Beverages">
<option value = "Milk">Milk</option>
<option value = "Fresh Juice">Fresh Juice</option>
<option value = "Ice Cream">Ice Cream</option>
<option value = "Coffee">Coffee</option>
<option value = "Carbonated Can Drink">Carbonated Can Drink</option>
<option value = "Water">Water</option>
</optgroup>
</select>
<br/>
</td>
<td>
<B>Dine In or Take Away : </B>
<select class="status">
<optgroup label="DEFAULT">
<option value = "NONE">NONE</option>
</optgroup>
<optgroup label="Status">
<option value = "Dine In">Dine In</option>
<option value = "Take Away">Take Away</option>
</optgroup>
</select>
<br/>
<B>Dine In or Take Away : </B>
<select class="status">
<optgroup label="DEFAULT">
<option value = "NONE">NONE</option>
</optgroup>
<optgroup label="Status">
<option value = "Dine In">Dine In</option>
<option value = "Take Away">Take Away</option>
</optgroup>
</select>
<br/>
</td>
</tr>
</table>
<br/>
<br/>
<input type="submit" id="btngo" value="Go" />
<br/>
</body>
</html>
"newPageTest.html" page.
< script type = "text/javascript" >
function parseQuery(str) {
if (typeof str != "string" || str.length == 0) return {};
var s = str.split("&");
var s_length = s.length;
var bit, query = {},
first, second;
for (var i = 0; i < s_length; i++) {
bit = s[i].split("=");
first = decodeURIComponent(bit[0]);
if (first.length == 0) continue;
second = decodeURIComponent(bit[1]);
if (typeof query[first] == "undefined") query[first] = second;
else if (query[first] instanceof Array) query[first].push(second);
else query[first] = [query[first], second];
}
return query;
}
//Function to update "showdata" div with URL Querystring parameter values
function passParameters() {
window.onload = passParameters;
var query = parseQuery(window.location.search);
var data = "<b>Food Beverages:</b> " + query.foodbeverage + " <b>Dine/Takeaway:</b> " + query.status;
document.getElementById("showdata").innerHTML = data;
}
<
/script>
<!DOCTYPE html>
<html>
<body>
<div id="showdata"></div>
</body>
</html>
I find 2 mistake from your code.
Put the window.onload = passParameters; outside of your passParameters function.
For example:
function passParameters() {
var query = parseQuery(window.location.search);
var data = "<b>Food Beverages:</b> " + query.foodbeverage + " <b>Dine/Takeaway:</b> " + query.status;
document.getElementById("showdata").innerHTML = data;
}
window.onload = passParameters;
The parseQuery return {"?foodbeverage":"Chicken Chop","foodbeverage":"Pasta","status":["Dine In","Take Away"]} from input query ?foodbeverage=Chicken%20Chop&foodbeverage=Pasta&status=Dine%20In&status=Take%20Away
You may want to add str = str.substr(1); before var s = str.split("&");
For example
function parseQuery(str) {
if (typeof str != "string" || str.length == 0) return {};
str = str.substr(1);
var s = str.split("&");
var s_length = s.length;
var bit, query = {},
first, second;
for (var i = 0; i < s_length; i++) {
bit = s[i].split("=");
first = decodeURIComponent(bit[0]);
if (first.length == 0) continue;
second = decodeURIComponent(bit[1]);
if (typeof query[first] == "undefined") query[first] = second;
else if (query[first] instanceof Array) query[first].push(second);
else query[first] = [query[first], second];
}
return query;
}
I have one select box with a list of games and the other with filled with a list of consoles. Each game has the possibility to belong to a number of consoles. I'm looking to filter the second select box according to whichever game is selected in the first.
So for instance if I select a game like Forza Horizon that belongs to more than one console then the console select box would filter just those and hide the others.
Right now I have it setup where on a select event it captures the text value of the game. From there I figured to filter through their respective optgroup's label property, which is the console it belongs to. I just can't seem to figure out how to retrieve the other possible consoles it may belong to other than the selected option.
Fiddle
<select class="game-select">
<option value="">Select a game</option>
<optgroup label="PS4"></optgroup>
<option value="1">Forza Horizon 2</option>
<option value="2">The Last of Us</option>
<option value="3">Bioshock Infinite</option>
</optgroup>
<optgroup label="Xbox One">
<option value="1">Forza Horizon</option>
<option value="2">Halo</option>
<option value="3">Bioshock Infinite</option>
</optgroup>
</select>
<select class="console-select">
<option value="">Select a console</option>
<option value="1">PS4</option>
<option value="2">Xbox One</option>
</select>
JS
$(function() {
var gameConsoles = $(".console-select").html();
$(".game-select").on("change", function() {
var game = $(this).find("option:selected").text(),
options = gameConsoles.filter().html(); // Not sure how to filter
if (options) {
$(".console-select").html(options);
} else {
$(".console-select").empty();
}
});
});
Update 2
You can do something like this
$(function () {
var consoleSelect = $('.console-select'),
gameConsoleOptions = $('.console-select option');
$(".game-select").on("change", function () {
var selectedGame = $(this).find("option:selected").data('game'),
games = [],
selectedCategory = $(this).find("option:selected").closest('optgroup').attr('label');
if (selectedGame) {
games = $.makeArray($(this).find('option[data-game="' + selectedGame + '"]').map(function () {
return $(this).closest('optgroup').attr('label');
}));
}
if (games.length) {
gameConsoleOptions.hide();
gameConsoleOptions.filter(function (i, v) {
return games.indexOf($(v).text()) != -1;
}).show();
consoleSelect.find('option:contains('+selectedCategory+')').prop('selected', 'selected');
} else {
gameConsoleOptions.show();
}
});
});
Here is a demo http://jsfiddle.net/dhirajbodicherla/m178xpc3/11/
Update
I added a code to each game using the data-* attribute.
For example the below two games have the same data-game attribute which can be used to figure out that these two are of the same category.
<option value="1" data-game="FH">Forza Horizon 2</option>
<option value="2" data-game="FH">Forza Horizon</option>
Complete example
<select class="game-select">
<option value="">Select a game</option>
<optgroup label="PS4">
<option value="1" data-game="FH">Forza Horizon 2</option>
<option value="2" data-game="LU">The Last of Us</option>
<option value="3" data-game="BI">Bioshock Infinite</option>
</optgroup>
<optgroup label="Xbox One">
<option value="1" data-game="FH">Forza Horizon</option>
<option value="2" data-game="HA">Halo</option>
<option value="3" data-game="BI">Bioshock Infinite</option>
</optgroup>
</select>
<select class="console-select">
<option value="">Select a console</option>
<option value="1">PS4</option>
<option value="2">Xbox One</option>
</select>
This is the script
$(function () {
var gameConsoleOptions = $('.console-select option');
$(".game-select").on("change", function () {
var selectedGame = $(this).find("option:selected").data('game'), games = [];
console.log(selectedGame);
if (selectedGame) {
games = $.makeArray($(this).find('option[data-game="' + selectedGame + '"]').map(function () {
return $(this).closest('optgroup').attr('label');
}));
}
console.log(games);
if (games) {
gameConsoleOptions.hide();
gameConsoleOptions.filter(function (i, v) {
return games.indexOf($(v).text()) != -1;
}).show();
} else {
gameConsoleOptions.show();
}
});
});
Here is a demo http://jsfiddle.net/dhirajbodicherla/m178xpc3/10/
You can do something like this
$(function () {
var gameConsoleOptions = $('.console-select option');
$(".game-select").on("change", function () {
var label = $(this).find("option:selected").closest('optgroup').prop('label');
if (label) {
gameConsoleOptions.hide();
gameConsoleOptions.filter(function (i, v) {
return $(v).text() === label;
}).show();
}else{
gameConsoleOptions.show();
}
});
});
Here is a demo http://jsfiddle.net/dhirajbodicherla/m178xpc3/5/
The code should speak for itself but it all comes down to multiple jQuery filter functions and a clone of the set with options. One advice: Use data attributes instead of relying on the option element text. I updated the fiddle, see link below.
$(function() {
var gameConsoles = $(".console-select");
var consoleOptions = gameConsoles.find('option').clone();
var gameSelect = $(".game-select").on("change", function() {
var game = $(this).find("option:selected").text();
var filteredOptions = $();
gameSelect.find('optgroup').filter(function() {
return $(this).find('option').filter(function() {
return $(this).text() == game;
}).length;
}).each(function () {
var label = $(this).attr('label');
filteredOptions = filteredOptions.add(consoleOptions.filter(function() {
return $(this).text() == label;
}));
});
gameConsoles.html(filteredOptions);
});
});
Fiddle update
Is that what you wanted?
$(".game-select").on("change", function() {
var o = $('option:selected', $(this));
if (!o.val()) {
$('.game-select optgroup').show();
$('.console-select option').show();
return;
}
$('.console-select > option').hide();
var a = $('option:contains("' + o.text() + '")').filter(function() {
return $(this).text() == o.text();
}).each(function() {
var t = $(this);
var l = t.parent().attr('label');
$('.console-select option:contains("' + l + '")').filter(function() {
return l == $(this).text();
}).show();
});
});
$(".console-select").on("change", function() {
var o = $('option:selected', $(this));
if (!o.val()) {
$('.game-select optgroup').show();
$('.console-select option').show();
return;
}
$('.game-select optgroup').hide();
console.log($('.game-select optgroup[label="' + o.text() + '"]'));
$('.game-select optgroup[label="' + o.text() + '"]').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="game-select">
<option value="">Select a game</option>
<optgroup label="PS4">
<option value="c1">Forza Horizon 2</option>
<option value="c2">The Last of Us</option>
<option value="c3">Bioshock Infinite</option>
</optgroup>
<optgroup label="Xbox One">
<option value="s1">Forza Horizon</option>
<option value="s2">Halo</option>
<option value="s3">Bioshock Infinite</option>
</optgroup>
</select>
<select class="console-select">
<option value="">Select a console</option>
<div>
<option value="c">PS4</option>
<option value="s">Xbox One</option>
</div>
</select>
I have 2 dropdown menus, and I need to compose a link with it's values.
Here is the code:
<form id="dropdown1">
<select id="linha">
<option value="G12">Option 1</option>
<option value="G11">Option 2</option>
<option value="H89">Option 3</option>
</select>
<select id="dia">
<option value="all">Every day</option>
<option value="work">working days</option>
<option value="sat">saturday</option>
<option value="sun">sunday</option>
</select>
</form>
I need something in JavaScript to "compose" a link with http://somewebsite.com/*selected_linha_value*/*selected_dia_value*
How can I do that?
<select name="dia" id="dia">
<option value="all">Every day</option>
<option value="http://stackoverflow.com">working days</option>
<option value="http://anotherSite.com">saturday</option>
<option value="http://anotherSite2.com">sunday</option>
</select>
<script>
$("#dia").change(function () {
var selctedValue = "";
$("select option:selected").each(function () {
selctedValue += $(this).val();
window.location.href = selctedValue;
});
});
i think u need something like this.
<script type="text/javascript">
params = getParams();
var name1 = unescape(params["linha"]);
switch(name1)
{
case "g12":
window.location = "http://www.google.com"
}
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
Its not the full code. It will give you some idea. If you have any doubt just comment
Take a look at: http://jsfiddle.net/ERHhA/
You can use jQuery val() to get the value of the select boxes. Then just append these values to the base url.
var url = "http://somewebsite.com/" + $('#linha').val() + "/" + $('#dia').val();
What about this one?
function make_url(){
var linha = document.getElementById('linha').value;
var dia = document.getElementById('dia').value;
var url=window.location.href;
var pos=url.indexOf('?');
if (pos>-1){
url = url.substr(0,pos);
}
//alert(url + '?linha='+linha+'&dia='+dia); return;
document.location.href = url + '?linha='+linha+'&dia='+dia;
}
fiddle
HTML
<div class="container">
<select class="small-nav">
<option value="" selected="selected">Go To</option>
<option value="http://whiterabbitexpress.com">Services</option>
<option value="http://shop.whiterabbitjapan.com">Shop</option>
</div><!-- container -->
JScript:
$(".small-nav").change(function() {
window.location = $(this).find("option:selected").val();
});