jQuery looping through an object array - javascript

I have the following HTML and JS, I am trying to only display elements if they match the criteria selected in the <select> tags. I am fairly sure that my IF statement currently would not achieve what I am trying to do even if it did work, however I am struggling to think of the logic for this.
HTML:
<select id="price-from" class="form-control">
<option selected value="£500">£500</option>
<option value="1000">£1,000</option>
<option value="2000">£2,000</option>
<option value="3000">£3,000</option>
<option value="4000">£4,000</option>
<option value="5000">£5,000</option>
<option value="10000">£10,000</option>
<option value="20000">£20,000</option>
</select>
<p>To</p>
<select id="price-to" class="form-control">
<option value="500">£500</option>
<option value="1000">£1,000</option>
<option value="2000">£2,000</option>
<option value="3000">£3,000</option>
<option value="4000">£4,000</option>
<option value="5000">£5,000</option>
<option value="10000">£10,000</option>
<option selected value="20000">£20,000</option>
</select>
JavaScript:
$(document).ready(function(){
var product1 = {title:"Cute Gnome", type:"Cute", price:"3999"};
var product2 = {title:"Funny Gnome", type:"Funny", price:"5999"};
var product3 = {title:"Seasonal Gnome", type:"Seasonal", price:"12999"};
var product4 = {title:"Horror Gnome", type:"Horror", price:"7999"};
var productArray = [
product1, product2, product3, product4
];
var len = productArray.length;
for (var i = 0; i < len; i++) {
if ($("#price-from").val() < productArray[i].price && $("#price-to").val() > productArray[i].price){
//Loop through code and only output objects between both price criteria
}
}
});

You need to bind the change event to select elements. Additionally you should to convert string to Number before comparison. use .filter()
$('select').on('change', function() {
var priceFrom = +$("#price-from").val(); //Convert value to Number
var priceTo = +$("#price-to").val(); //Convert value to Number
//Filter the elements which matches the condition
var matchingElemets = productArray.filter(function(pd) {
var p = +pd.price; //Convert value to Number
return p >= priceFrom && p <= priceTo;
});
console.clear();
console.log(matchingElemets);
});
$(document).ready(function() {
var product1 = {
title: "Cute Gnome",
type: "Cute",
price: "3999"
};
var product2 = {
title: "Funny Gnome",
type: "Funny",
price: "5999"
};
var product3 = {
title: "Seasonal Gnome",
type: "Seasonal",
price: "12999"
};
var product4 = {
title: "Horror Gnome",
type: "Horror",
price: "7999"
};
var productArray = [
product1, product2, product3, product4
];
$('select').on('change', function() {
var priceFrom = +$("#price-from").val(); //Convert value to Number
var priceTo = +$("#price-to").val(); //Convert value to Number
var matchingElemets = productArray.filter(function(pd) {
var p = +pd.price; //Convert value to Number
return p >= priceFrom && p <= priceTo;
});
console.clear();
console.log(matchingElemets)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="price-from" class="form-control">
<option selected value="£500">£500</option>
<option value="1000">£1,000</option>
<option value="2000">£2,000</option>
<option value="3000">£3,000</option>
<option value="4000">£4,000</option>
<option value="5000">£5,000</option>
<option value="10000">£10,000</option>
<option value="20000">£20,000</option>
</select>
<p>To</p>
<select id="price-to" class="form-control">
<option value="500">£500</option>
<option value="1000">£1,000</option>
<option value="2000">£2,000</option>
<option value="3000">£3,000</option>
<option value="4000">£4,000</option>
<option value="5000">£5,000</option>
<option value="10000">£10,000</option>
<option selected value="20000">£20,000</option>
</select>

Code below add it to the onchange Attribute on both of the selects and you have a Framework Independent solution that Returns the list.
Ofcourse you will have to add your own logic to Change displayed products.
Do note that haveing a .ready doesnt really do annything here since it is (should be) an Event driven Action.
function filter()
{
//reduces calls to DOM in for loop
var min = document.getElementById("price-from").value;
var max = document.getElementById("price-to").value;
var length = productArray.length;
var products = [];
for (var i = 0; i < length; i++) {
if (min <= productArray[i].price && max > productArray[i].price) {
products.push(productArray[i]);
}
}
return products;
}

You presumably want to do this whenever one of the select boxes is changed, so the thing to do is hook into the change event on both and run your code. You dont specify what you mean by "output" so I'll just output to the console.
var product1 = {title:"Cute Gnome", type:"Cute", price:"3999"};
var product2 = {title:"Funny Gnome", type:"Funny", price:"5999"};
var product3 = {title:"Seasonal Gnome", type:"Seasonal", price:"12999"};
var product4 = {title:"Horror Gnome", type:"Horror", price:"7999"};
var productArray = [
product1, product2, product3, product4
];
$('select').on('change',function(){
var from = parseInt($('#price-from').val(),10);
var to = parseInt($('#price-to').val(),10);
var matches = productArray.filter(function(x){
var price = parseInt(x.price,10);
return from <= price && to >= price;
});
console.clear();
console.log(matches);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="price-from" class="form-control">
<option selected value="£500">£500</option>
<option value="1000">£1,000</option>
<option value="2000">£2,000</option>
<option value="3000">£3,000</option>
<option value="4000">£4,000</option>
<option value="5000">£5,000</option>
<option value="10000">£10,000</option>
<option value="20000">£20,000</option>
</select>
<p>To</p>
<select id="price-to" class="form-control">
<option value="500">£500</option>
<option value="1000">£1,000</option>
<option value="2000">£2,000</option>
<option value="3000">£3,000</option>
<option value="4000">£4,000</option>
<option value="5000">£5,000</option>
<option value="10000">£10,000</option>
<option selected value="20000">£20,000</option>
</select>
Roughly what this code is doing is as follows
var from = parseInt($('#price-from').val(),10);
var to = parseInt($('#price-to').val(),10);
These two lines take the values of your two select boxes, and parse their value to an integer. See parseInt
var matches = productArray.filter(function(x){
var price = parseInt(x.price,10);
return from <= price && to >= price;
});
This line uses filter to get the items from your original list which fall within the range of prices selected. See Array.filter
console.clear();
console.log(matches);
These lines simply clear and then output the items from the array which match your prices to the console. You could easily iterate over this list and output to the page iif required.

Related

Is it possible to store data in function to an object literal by passing argument to a function?

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.

Multiple Drop Down Values Won't Display In New HTML Page

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;
}

select.getElementsByTagName except for a certain option

Option List
I have an problem where my Random Option Picker picks a certain option that I don't want. How do I mitigate this?
var select = document.getElementById('edit-categories');
var items = select.getElementsByTagName('option');
var index = Math.floor(Math.random() * items.length + 1);
return select.selectedIndex = index;
The option that I want my random picker to ommit is : value="_none"
Use querySelectorAll along with :not and an attribute selector:
var items = select.querySelectorAll('option:not([value="_none"])');
var select = document.querySelector('select');
var items = select.querySelectorAll('option:not([value="_none"])');
console.log(items);
<select>
<option value="_none">--</option>
<option value="water">Water</option>
<option value="waste">Waste</option>
</select>
As an alternative, you can also use Array.prototype.filter (since It's a lot easier to pollyfil filter than the [not] selector):
var opts = [].filter.call(document.getElementById('edit-categories').options, function(opt){return opt.value != '_none'})
console.log(opts);
<select id="edit-categories">
<option value="_none">None
<option value="foo">Foo
<option value="foo">Bar
</select>
You can add a while loop just before setting the index :
var select = document.getElementById('edit-categories');
var items = select.getElementsByTagName('option');
var index = Math.floor(Math.random() * items.length);
while (items[index].value == '_none') {
index = Math.floor(Math.random() * items.length);
}
select.selectedIndex = index;
<select id="edit-categories">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="_none">none</option>
<option value="4">4</option>
</select>

How to dynamically generate a dropdown menu [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In my php, I have created two dropdown or selection lists. My drop down list below:
<select name="food">
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
</select>
<select name="type">
<option value="">--</option>
<option value="Apple">Apple</option>
<option value="Lettuce">Lettuce</option>
<option value="Orange">Orange</option>
<option value="Tomato">Tomato</option>
<option value="Carrots">Carrots</option>
<option value="Mango">Mango</option>
</select>
m one page to the next.
It's possible to do this using jQuery, but it will quickly become unmanageable in a large-scale app or website.
If you go this route, I would avoid using two different select boxes, as this will force you to choose two different names for the form POST, unless you use more jQuery hackery to remedy this problem.
My suggestion is to look at a lightweight JS framework. Knockoutjs has what you need.
Look at this JSFiddle.
var fruitOpts = ["Apple", "Orange", "Mango"];
var vegOpts = ["Lettuce", "Tomato", "Carrots"];
$("#food").change(function () {
var val = $(this).val();
if (val === "") {
return;
}
$("#type").find('option').not(':first').remove().end();
$.each(val === "Fruits" ? fruitOpts : vegOpts, function (i, v) {
$("#type").append("<option value=\"" + v + "\">" + v + "</option>");
});
$.each(val === "Fruits" ? vegOpts : fruitOpts, function (i, v) {
$("#type").append("<option value=\"" + v + "\">" + v + "</option>");
});
});
It's version for two different php pages:
1.php
<script src="1.js"></script>
<a id='link' href='2.php'>go to another page</a>
<select id="food" name="food" onchange="selectFoodType()">
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
<option value="Berries">Berries</option>
</select>
1.js
function selectFoodType()
{
var link = $('#link');
var type = $('select#food option:selected').val();
link.attr('href', link.attr('href') + '?type=' + type);
}
2.php
<script src="2.js"></script>
<select id='type' name="type" data-type='<?=$_GET['type']?>'>
<option value="">--</option>
<option data-type='Fruits' value="Apple">Apple</option>
<option data-type='Vegetables' value="Tomato">Tomato</option>
<option data-type='Vegetables' value="Carrots">Carrots</option>
<option data-type='Berries' value="Strawberry">Strawberry</option>
</select>
2.js
$(function() {
var type = $('select#type').data('type');
var itemsId = document.getElementById("type");
var items = itemsId.getElementsByTagName("option");
var selected_type = [], other_types = [];
selected_type[0] = items[0];
for (var i = 1; i < items.length; i++){
if ($(items[i]).data('type') === type) {
selected_type.push(items[i]);
continue;
}
other_types.push(items[i]);
}
selected_type = selected_type.sort(sortByName);
other_types = other_types.sort(sortByName);
$.merge(selected_type, other_types);
var list = '';
for (i=0; i<selected_type.length; i++) {
list += selected_type[i].outerHTML;
}
$(items).remove();
$(itemsId).append(list);
});
function sortByName(a, b) {
if (a.text > b.text) return 1;
else if (a.text < b.text) return -1;
return 0;
}
You should assign all Fruits and Vegetables contents in JavaScript object and display related contents of food value in another drop down, see below demo
Food:
<select name="food" id="food">
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
</select>
Content
<select name="contents" id="contents">
<option value="">...</option>
</select>
JS code
var data = {
'Fruits':['Apple', 'Lettuce', 'Orange', 'Mango'],
'Vegetables': ['Tomato', 'Carrots']
};
document.getElementById("food").onchange = function(Event){
var contents = document.getElementById("contents");
contents.innerHTML = "";
for(var i in data[this.value]){
var option = document.createElement("option");
option.setAttribute('value',data[this.value][i]);
option.text = data[this.value][i];
contents.appendChild(option);
}
var expect_data = Event.target.value == "Fruits" ? "Vegetables" : "Fruits";
for(var i in data[expect_data]){
var option = document.createElement("option");
option.setAttribute('value',data[expect_data][i]);
option.text = data[expect_data][i];
contents.appendChild(option);
}
}
FIDDLE DEMO
you need to use JQuery for this purpose.
See My Solution: http://jsfiddle.net/inventorx/YU4vJ/
Code Here:
HTML
<select name="food" >
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
</select>
<select name='type' >
<option>-- Select Food Type --</option>
</select>
<select id='Fruits' style='display:none' >
<option value="">--</option>
<option value="Apple">Apple</option>
<option value="Orange">Orange</option>
<option value="Mango">Mango</option>
</select>
<select id='Vegetables' style='display:none' >
<option value="">--</option>
<option value="Lettuce">Lettuce</option>
<option value="Tomato">Tomato</option>
<option value="Carrots">Carrots</option>
</select>
JQUERY
$(document).ready(function(){
$("select[name='food']").on("change", function(){
var value = $(this).val();
$("select[name='type']").html($("#" + value).html());
});
});
Another option.
The list splits into two arrays: food, corresponding to the selected type; and does not correspond to the selected type. Each of these arrays, in turn, is sorted by name:
JSFIDDLE
HTML:
<select id="food" name="food" onchange="selectFoodType()">
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
<option value="Berries">Berries</option>
</select>
<select id='type' name="type">
<option value="">--</option>
<option data-type='Fruits' value="Apple">Apple</option>
<option data-type='Vegetables' value="Lettuce">Lettuce</option>
<option data-type='Vegetables' value="Tomato">Tomato</option>
<option data-type='Berries' value="Strawberry">Strawberry</option>
</select>
JQuery:
function selectFoodType()
{
var type = $('select#food option:selected').val();
var itemsId = document.getElementById("type");
var items = itemsId.getElementsByTagName("option");
var selected_type = [], other_types = [];
selected_type[0] = items[0];
for (var i = 1; i < items.length; i++){
if ($(items[i]).data('type') === type) {
selected_type.push(items[i]);
continue;
}
other_types.push(items[i]);
}
selected_type = selected_type.sort(sortByName);
other_types = other_types.sort(sortByName);
$.merge(selected_type, other_types);
var list = '';
for (i=0; i<selected_type.length; i++) {
list += selected_type[i].outerHTML;
}
$(items).remove();
$(itemsId).append(list);
}
function sortByName(a, b) {
if (a.text > b.text) return 1;
else if (a.text < b.text) return -1;
return 0;
}

Compose a link based in select's option value

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();
});

Categories