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 this drop down that I compare with an array. If a value in the array matches the text of one of the options in the dropdown, then it is selected:
JS -Step One:
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns ('topicSelect',topicArray);
Dropdown
<select class="topicSelect" multiple>
<optgroup label="Crops">
<option selected="" value=""></option>
<option value="Apiculture">Apiculture</option>
<option value="Apples">Apples</option>
<option value="Aquaculture">Aquaculture</option>
<option value="Blueberries">Blueberries</option>
</optgroup>
<optgroup label="Add Option" class="youOwn">
<option value="own">Add Your Option</option>
</optgroup>
</select>
JS - Step Two:
function populateExistingDropDowns(dd, array) {
var select = document.getElementsByClassName(dd);
for (var d = 0; d < array.length; d++) {
for (var i = 0; i < select[0].options.length; i += 1) {
if (select[0].options[i].text === array[d]) {
select[0].options[i].selected = true;
}
}
}
}
Here comes my issue: The the code showed above works just fine, but I would like to be able to add a new option if an option with the same array value doesn't exist. In the example shown above, there are two values ('Apple' and 'Tomatoes") values in the array. When I iterate through the array and the dropdown, the 'Apple' option is selected, but, how can I then add a new 'Tomatoes' options, and then select it also? Thanks in advance, please let me know if more details are needed.
I would like to be able to add a new option if an option with the same array value doesn't exist..
you can clone an option node modify it and append it to parent node,
in the snippet I added a dedicated function;
function populateExistingDropDowns(dd, array) {
var select = document.getElementsByClassName(dd);
outer:
for (var d = 0; d < array.length; d++) {
for (var i = 0; i < select[0].options.length; i += 1) {
if (select[0].options[i].text === array[d]) {
select[0].options[i].selected = true;
continue outer;
}
//if you haven't matched and are in last loop
if ( i === select[0].options.length - 1) {
addOpt(array[d], select[0].options[i])
}
}
}
}
function addOpt(x,clone){
var node = clone.cloneNode();
node.selected= true;
node.value= node.innerHTML= x;
clone.parentNode.appendChild(node)
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns ('topicSelect',topicArray);
<select class="topicSelect" multiple>
<optgroup label="Crops">
<option selected="" value=""></option>
<option value="Apiculture">Apiculture</option>
<option value="Apples">Apples</option>
<option value="Aquaculture">Aquaculture</option>
<option value="Blueberries">Blueberries</option>
</optgroup>
<optgroup label="Add Option" class="youOwn">
<option value="own">Add Your Option</option>
</optgroup>
</select>
One approach, using ES6 syntax is the following:
function populateExistingDropDowns(dd, array) {
// using 'let' rather than 'var' to declare variables,
// using document.querySelector(), rather than
// getElementsByClassName(), because d.qS has support
// in IE8 (whereas it does not support
// getElementsByClassName()); however here we get the
// first element that matches the selector:
let dropdown = document.querySelector('.' + dd),
// retrieving the collection of option elements,
// HTMLSelectElement.options, and converting that
// collection into an Array using Array.from():
options = Array.from(dropdown.options);
// iterating over each of the topics in the passed-in
// array, using Array.prototype.forEach():
array.forEach(function(topic) {
// filtering the array of <option> elements to keep
// only those whose text property is equal to the
// current topic (from the array):
let opts = options.filter(opt => topic === opt.text);
// if the opts Array has a truthy non-zero length:
if (opts.length) {
// we iterate over the returned filtered Array
// and, using Arrow function syntax, set each
// node's selected property to true:
opts.forEach(opt => opt.selected = true);
} else {
// otherwise, if the current topic returned no
// <option> elements, we find the <optgroup>
// holding the 'Crops' and append a new Child
// using Node.appendChild(), and the new Option()
// constructor to set the option-text, option-value
// default-selected property and selected property:
dropdown.querySelector('optgroup[label=Crops]')
.appendChild(new Option(topic, topic, true, true));
}
});
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns('topicSelect', topicArray);
function populateExistingDropDowns(dd, array) {
let dropdown = document.querySelector('.' + dd),
options = Array.from(dropdown.options);
array.forEach(function(topic) {
let opts = options.filter(opt => topic === opt.text);
if (opts.length) {
opts.forEach(opt => opt.selected = true);
} else {
dropdown.querySelector('optgroup[label=Crops]')
.appendChild(new Option(topic, topic, true, true));
}
});
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns('topicSelect', topicArray);
<select class="topicSelect" multiple>
<optgroup label="Crops">
<option value="Apiculture">Apiculture</option>
<option value="Apples">Apples</option>
<option value="Aquaculture">Aquaculture</option>
<option value="Blueberries">Blueberries</option>
</optgroup>
<optgroup label="Add Option" class="youOwn">
<option value="own">Add Your Option</option>
</optgroup>
</select>
JS Fiddle demo.
To recompose the above, using ES5:
function populateExistingDropDowns(dd, array) {
// using 'var' to declare variables:
var dropdown = document.querySelector('.' + dd),
// using Array.prototype.slice(), with
// Function.prototype.call(), to convert the collection
// of <option> element-nodes into an Array:
options = Array.prototype.slice.call(dropdown.options, 0);
array.forEach(function(topic) {
// using the anonymous functions available to the
// Array methods, rather than Arrow functions,
// but doing exactly the same as the above:
var opts = options.filter(function(opt) {
return topic === opt.text
});
if (opts.length) {
opts.forEach(function(opt) {
opt.selected = true;
});
} else {
dropdown.querySelector('optgroup[label=Crops]')
.appendChild(new Option(topic, topic, true, true));
}
});
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns('topicSelect', topicArray);
function populateExistingDropDowns(dd, array) {
var dropdown = document.querySelector('.' + dd),
options = Array.prototype.slice.call(dropdown.options, 0);
array.forEach(function(topic) {
var opts = options.filter(function(opt) {
return topic === opt.text
});
if (opts.length) {
opts.forEach(function(opt) {
opt.selected = true;
});
} else {
dropdown.querySelector('optgroup[label=Crops]')
.appendChild(new Option(topic, topic, true, true));
}
});
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns('topicSelect', topicArray);
<select class="topicSelect" multiple>
<optgroup label="Crops">
<option value="Apiculture">Apiculture</option>
<option value="Apples">Apples</option>
<option value="Aquaculture">Aquaculture</option>
<option value="Blueberries">Blueberries</option>
</optgroup>
<optgroup label="Add Option" class="youOwn">
<option value="own">Add Your Option</option>
</optgroup>
</select>
JS Fiddle demo.
References:
Array.from().
Array.prototype.filter().
Array.prototype.forEach().
Arrow functions.
document.querySelector().
HTMLOptionElement.
HTMLSelectElement.
let statement.
Node.appendChild().
Option() Constructor.
var statement.
Thank you all that responded to my question. I ended up using this instead:
function populateExistingDropDowns(dd, array) {
var select = document.getElementsByClassName(dd);
var opt = document.createElement('option');
for (var d = 0; d < array.length; d++) {
for (var q = 0; q < select[0].length; q++) {
if (select[0].options[q].text !== array[d]) {
opt.value = array[d];
opt.text = array[d];
select[0].children[1].appendChild(opt);
opt.selected = true;
} else {
select[0].options[q].selected = true;
}
}
}
}
Fiddle
I have a multi part form to load color options based on size selection however it will not add values to the option tag and I cant seem to find the solution. What I would like is.
To add values to the option tags example:
option value="X">Clear,option value="T">Smoke,option value="GS">Gunsmoke
Output as html the selected options text so i can display to client their selections in a readable format before they submit the final step.
Any help would be greatly appreciated. Thanks
My Code
var Vest_10_08 = new Array("Select Color", "Clear", "Smoke", "Gunsmoke");
var Vest_10_10 = new Array("Select Color", "Clear", "Smoke", "Gunsmoke");
var Vest_10_12 = new Array("Select Color", "Clear", "Smoke", "Gunsmoke");
var Vest_10_14 = new Array("Select Color", "Clear", "Smoke");
var Vest_10_16 = new Array("Select Color", "Clear", "Smoke");
$(document).ready(function () {
//Populate Select Items
$('#SelectSize').change(function () {
populateSelect(), populatePart();;
});
$('#SelectHardware').change(function () {
populatePart();
});
$('#SelectColor').change(function () {
populatePart();
});
function populateSelect() {
SelectSize = $('#SelectSize').val();
$('#SelectColor').html('');
eval(SelectSize).forEach(function (t) {
$('#SelectColor').append('<option>' + t + '</option>');
});
}
function populatePart() {
SelectSize = $('#SelectSize').val();
SelectHardware = $('#SelectHardware').val();
SelectColor = $('#SelectColor').val();
document.getElementById('item_name').value = (SelectSize + '66' + SelectHardware + SelectColor)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select id="SelectSize" name="SelectSize" required="">
<option selected="selected">Select Size</option>
<option value="Vest_10_08">10 tall X 14 wide</option>
<option value="Vest_10_10">14 tall X 14 wide</option>
<option value="Vest_10_12">16 tall X 14 wide</option>
<option value="Vest_10_14">16 tall X 16 wide</option>
<option value="Vest_10_16">18 tall X 16 wide</option>
</select>
<br>
<br>
<select id="SelectHardware" name="SelectHardware" required="">
<option selected="selected">Select Hardware</option>
<option value="C">Chrome</option>
<option value="SB">Black</option>
</select>
<br>
<br>
<select id="SelectColor" name="SelectColor" required=""></select>
<br>
<br>
<input id="item_name" name="item_name" type="text" style="width: 200px" />
First of all, it's generally considered a bad practice to use eval in general. A good re-write could use objects to store your values instead of using individually named variables. You can also use objects to store the value and display properties.
Something like this...
var vestData = {
'Vest_10_08':[
{
value:'',
text:'Select Color'
},
{
value:'S',
text:'Smoke'
},
{
value:'GS',
text:'Gun Smoke'
}
],
'Vest_10_10':[
// ...
]
};
However, since you have duplicate items with the same values you might want one master object to reference the internal values to the display values like this.
var colorNames = {
'C':'Clear',
'S':'Smoke',
'GS':'Gun Smoke'
}
var colorOptions = {
'Vest_10_08':['C','S','GS'],
'Vest_10_10':['C','S','GS'],
'Vest_10_12':['C','S','GS'],
'Vest_10_14':['C','S'],
'Vest_10_16':['C','S']
};
$(document).ready(function () {
//Populate Select Items
$('#SelectSize').change(function () {
populateSelect(), populatePart();;
});
$('#SelectHardware').change(function () {
populatePart();
});
$('#SelectColor').change(function () {
populatePart();
});
function populateSelect() {
SelectSize = $('#SelectSize').val();
$('#SelectColor').html('<option value="">Select Color</option>');
colorOptions[SelectSize].forEach(function (t) {
$('#SelectColor').append('<option value="' + t + '">' + colorNames[t] + '</option>');
});
}
function populatePart() {
SelectSize = $('#SelectSize').val();
SelectHardware = $('#SelectHardware').val();
SelectColor = $('#SelectColor').val();
document.getElementById('item_name').value = (SelectSize + '66' + SelectHardware + SelectColor)
}
});
You must change your Arrays to compute objects instead of strings. E.g:
var Vest_10_08 = [
{ value: '', text: "Select Color" },
{ value: 'X', text: "Clear" },
{ value: 'T', text: "Smoke" },
{ value: 'GS', text: "Gunsmoke" }
];
And then, when you're looping through the Array:
$('#SelectColor').append('<option value="' + t.value + '">' + t.text + '</option>');
Note: Nothing to do with the question, but only a tip: I don't think it's a good idea to use eval, the way you're doing. You could simply use a keyvaluepair object, and then you'd use the ID as its key. E.g:
var vests = {
Vest_10_08: [
{ value: '', text: "Select Color" },
{ value: 'X', text: "Clear" },
{ value: 'T', text: "Smoke" },
{ value: 'GS', text: "Gunsmoke" }
],
Vest_10_10: [
/* (...) */
]
};
And then you could use it, instead of using eval, by doing:
vests[SelectSize].forEach(
var Vest_10_08 = new Array({name: "Select Color", option: 0}, {name: "Clear", option: "X"}, {name: "Smoke", option: "T"}, {name: "Gunsmoke", option: "GS"});
var Vest_10_10 = new Array({name: "Select Color", option: 0}, {name: "Clear", option: "X"}, {name: "Smoke", option: "T"}, {name: "Gunsmoke", option: "GS"});
var Vest_10_12 = new Array({name: "Select Color", option: 0}, {name: "Clear", option: "X"}, {name: "Smoke", option: "T"}, {name: "Gunsmoke", option: "GS"});
var Vest_10_14 = new Array({name: "Select Color", option: 0}, {name: "Clear", option: "X"}, {name: "Smoke", option: "T"});
var Vest_10_16 = new Array({name: "Select Color", option: 0}, {name: "Clear", option: "X"}, {name: "Smoke", option: "T"});
$(document).ready(function () {
//Populate Select Items
$('#SelectSize').change(function () {
populateSelect();
populatePart();
});
$('#SelectHardware').change(function () {
populatePart();
});
$('#SelectColor').change(function () {
populatePart();
});
function populateSelect() {
SelectSize = $('#SelectSize').val();
$('#SelectColor').html('');
eval(SelectSize).forEach(function (t) {
$('#SelectColor').append('<option value=' + t.option + '>' + t.name + '</option>');
});
}
function populatePart() {
SelectSize = $('#SelectSize').val();
SelectHardware = $('#SelectHardware').val();
SelectColor = $('#SelectColor').val();
document.getElementById('item_name').value = (SelectSize + '66' + SelectHardware + SelectColor)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="SelectSize" name="SelectSize" required="">
<option selected="selected">Select Size</option>
<option value="Vest_10_08">10 tall X 14 wide</option>
<option value="Vest_10_10">14 tall X 14 wide</option>
<option value="Vest_10_12">16 tall X 14 wide</option>
<option value="Vest_10_14">16 tall X 16 wide</option>
<option value="Vest_10_16">18 tall X 16 wide</option>
</select>
<br>
<br>
<select id="SelectHardware" name="SelectHardware" required="">
<option selected="selected">Select Hardware</option>
<option value="C">Chrome</option>
<option value="SB">Black</option>
</select>
<br>
<br>
<select id="SelectColor" name="SelectColor" required=""></select>
<br>
<br>
<input id="item_name" name="item_name" type="text" style="width: 200px" />
Just put your Colors detail inside another object. You need not to duplicate all colors value inside all "Vest_10_*"
var Vest_10_08 = new Array("Select Color", "Clear", "Smoke", "Gunsmoke");
var Vest_10_10 = new Array("Select Color", "Clear", "Smoke", "Gunsmoke");
var Vest_10_12 = new Array("Select Color", "Clear", "Smoke", "Gunsmoke");
var Vest_10_14 = new Array("Select Color", "Clear", "Smoke");
var Vest_10_16 = new Array("Select Color", "Clear", "Smoke");
//New added
var Colors = {};
Colors['Select Color'] = '0';
Colors['Clear'] = 'X';
Colors['Smoke'] = 'T';
Colors['Gunsmoke'] = 'GS';
$(document).ready(function () {
//Populate Select Items
$('#SelectSize').change(function () {
populateSelect(), populatePart();;
});
$('#SelectHardware').change(function () {
populatePart();
});
$('#SelectColor').change(function () {
populatePart();
});
function populateSelect() {
SelectSize = $('#SelectSize').val();
$('#SelectColor').html('');
//Changes in this function
eval(SelectSize).forEach(function (t) {
console.log(t);
var value = Colors[t];
console.log(value);
$('#SelectColor').append('<option value="'+value+'">' + t + '</option>');
});
}
function populatePart() {
SelectSize = $('#SelectSize').val();
SelectHardware = $('#SelectHardware').val();
SelectColor = $('#SelectColor').val();
document.getElementById('item_name').value = (SelectSize + '66' + SelectHardware + SelectColor)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<select id="SelectSize" name="SelectSize" required="">
<option selected="selected">Select Size</option>
<option value="Vest_10_08">10 tall X 14 wide</option>
<option value="Vest_10_10">14 tall X 14 wide</option>
<option value="Vest_10_12">16 tall X 14 wide</option>
<option value="Vest_10_14">16 tall X 16 wide</option>
<option value="Vest_10_16">18 tall X 16 wide</option>
</select>
<br>
<br>
<select id="SelectHardware" name="SelectHardware" required="">
<option selected="selected">Select Hardware</option>
<option value="C">Chrome</option>
<option value="SB">Black</option>
</select>
<br>
<br>
<select id="SelectColor" name="SelectColor" required=""></select>
<br>
<br>
<input id="item_name" name="item_name" type="text" style="width: 200px" />
If you want to avoid "eval" than code is here :
http://jsfiddle.net/bhushankumar/0b4azsuf/2/
Use a template libary like underscore or handlebars or mustache. Its bad practice to generate html from javascript.
You can format your input in javascript and construct and object with array inside :
var choices = {1:["oneValue", "twoValue"], 2:["oneHtml", "twoHtml"]};
function addInputSelect(divName) {
var newDiv = document.createElement('div');
var selectHTML = "";
selectHTML="<select>";
for(i = 0; i < choices.length; i = i + 1) {
/* choices[1][i] for get the first object in array position i */
selectHTML += "<option value='" + choices[1][i] + "'>" + choices[2][i] + "</option>";
}
selectHTML += "</select>";
newDiv.innerHTML = selectHTML;
/* append the html constructed to the dom. (divName is the html div dynamicInput) */
document.getElementById(divName).appendChild(newDiv);
}
<!-- html -->
<div id="dynamicInput"></div>
<input type="button" value="Add" onclick="addInput('dynamicInput');" />
I have two fields customer category and customer type,
when I select one element in customer category , I need to display only a set of elements from customer type in the drop down and rest should not appear.
how do write it in javascript. Here is the one I tried but it doesnot yield proper result.
var custcategory = document.getElementById("custcatid");
var custtypes = document.getElementById('custtypeid').options;
alert('yes');
var n = custtypes.length;
var allowedtype;
if (custcategory.options[custcategory.selectedIndex].value == "ANALOGUE") {
alert('ANALOGUE');
allowedtype = 'CATV,CATV RURAL';
}
else if (custcategory.options[custcategory.selectedIndex].value == "COMMERCIAL") {
alert('COMMERCIAL');
allowedtype = ' ,3ST HOTEL,4ST HOTEL,5ST HOTEL';
}
else if (custcategory.options[custcategory.selectedIndex].value == "DAS") {
alert('DAS');
allowedtype = ' ,DAS PHASE1,DAS PHASE2,DAS PHASE3,DAS PHASE4';
}
else if (custcategory.options[custcategory.selectedIndex].value == "DTH") {
alert('DTH');
allowedtype = ' ,DTH';
}
var idx = 0;
for (var i = 0; i < n; i++) {
var type = custtypes[i].value;
var found = allowedtype.search(type);
if (found <= 0) {
custtypes[i].style.display = 'none';
}
else if (idx == 0) {
idx = 1;
document.getElementById('ctl00_uxPgCPH_custtype').selectedIndex = i;
}
}
alert('Done..!');
If I understand correctly, you are trying to filter a second select element based on what is selected in the first select element?
If so I put together the following snippet which might help you out. It can be probably be optimised further but it should help to get you started I feel.
(function () {
var CLASSES = {
categories: '.select__category',
types : '.select__types'
},
map = {
ANALOGUE: [
'CATV',
'CATV RURAL'
],
COMMERCIAL: [
'3ST HOTEL',
'4ST HOTEL',
'5ST HOTEL'
],
DAS: [
'DAS PHASE 1',
'DAS PHASE 2',
'DAS PHASE 3'
]
},
categorySelect = document.querySelector(CLASSES.categories),
typeSelect = document.querySelector(CLASSES.types),
filterTypes = function(val) {
// Based on a value filter the types select.
var opts = typeSelect.options,
allowedOpts = map[val];
typeSelect.value = allowedOpts[0];
for(var i = 0; i < opts.length; i++) {
if (allowedOpts.indexOf(opts[i].value) === -1) {
opts[i].hidden = true;
} else {
opts[i].hidden = false;
}
}
};
filterTypes(categorySelect.value);
categorySelect.addEventListener('change', function(e) {
filterTypes(this.value);
});
}());
<!DOCTYPE html>
<head></head>
<body>
<select id="categories" class="select__category">
<option value="ANALOGUE">Analogue</option>
<option value="COMMERCIAL">Commercial</option>
<option value="DAS">Das</option>
</select>
<select id="types" class="select__types">
<option value="CATV">Catv</option>
<option value="CATV RURAL">Catv Rural</option>
<option value="3ST HOTEL">3st Hotel</option>
<option value="4ST HOTEL">4st Hotel</option>
<option value="5ST HOTEL">5st Hotel</option>
<option value="DAS PHASE 1">Das Phase 1</option>
<option value="DAS PHASE 2">Das Phase 2</option>
<option value="DAS PHASE 3">Das Phase 3</option>
</select>
</body>
If you run the snippet, you'll see that making changes to the first will update the second select accordingly based on the defined map.
Hope this can help you out!
I need to create a menu of regions hat display two lists: a <select> for the region and another <select> for the available municipalities of that region. For this, I have a <form> and I update the municipalities through JavaScript. I have problems assigning the municipalities as <option>s of the second <select>. The option matrix of the menu doesn't accept the assignment of the values.
Here's the code.
HTML.
<html>
<head>
<title>
Página menú principal.
</title>
<?!= incluirArchivo('ArchivoJS'); ?>
</head>
<body onLoad = "preparar();">
<form id="formularioConductor" name="formularioConductor" method="post" enctype="multipart/form-data" autocomplete = "on">
<select name="menuDepartamento" id="menuDepartamento" tabindex="2" accesskey="e" onChange="municipiosDepartamento();">
<option value="x" selected="selected">ELIJA UN DEPARTAMENTO</option>
<option value="0">Antioquia</option>
<option value="1">Atlántico</option>
</select>
<select name="menuMunicipios" id="menuMunicipios" tabindex="3" disabled>
<option value=0>TODOS LOS MUNICIPIOS</option>
</select>
</form>
</body>
</html>
Javascript code:
<script lenguage="javascript">
function preparar() {
document.forms[0].elements.numeroLicencia.focus();
document.forms[0].elements.nombreConductor.disabled = true;
document.forms[0].elements.botonEnviar.disabled = true;
document.forms[0].elements.botonActualizar.disabled = true;
}
function municipiosDepartamento() {
var arregloMunicipiosDepartamento = new Array();
var posicionMunicipio = document.forms[0].elements.menuDepartamento.value;
arregloMunicipiosDepartamento = municipiosColombia(posicionMunicipio);
if(document.forms[0].elements.menuMunicipios.options.length > 1){
var totalMunicipios = document.forms[0].elements.menuMunicipios.length;
for (var i = 1; i < totalMunicipios; i ++){
document.forms[0].elements.menuMunicipios.options[1] = null;
}
}
if(document.forms[0].elements.menuDepartamento.value === "x"){
document.forms[0].elements.menuMunicipios.selectedItem = 0;
document.forms[0].elements.menuMunicipios.disabled = true;
}
else
{
document.forms[0].elements.menuMunicipios.options.length = arregloMunicipiosDepartamento.length;
for (var i = 0; i < arregloMunicipiosDepartamento.length; i ++) {
var opcionTemporal = new Option(arregloMunicipiosDepartamento[i], (i+1));
***document.forms[0].elements.menuMunicipios.options[i+1].text = opcionTemporal.text;
document.forms[0].elements.menuMunicipios.options[i+1].value = opcionTemporal.value;***
}
document.forms[0].elements.menuMunicipios.disabled = false;
}
}
function municipiosColombia(posicion) {
var antioquia, atlantico, arregloTodos, arregloMunicipiosDepartamento = new Array();
antioquia=["Medellín","Abejorral","Abriaqui","Alejandria"];
atlantico = ["Barranquilla","Baranoa","Campo De La Cruz","Candelaria"];
arregloTodos = [antioquia, atlantico];
arregloMunicipiosDepartamento=arregloTodos[posicion];
return arregloMunicipiosDepartamento;
}
</script>
I have highlighted the work that doesn't work.
The way I would do what you describe is to clear out the options each time and recreate the required ones, then add them into the particular select, like so:
var regions = {};
regions['A'] = ['mu', 'ni', 'ci', 'pal', 'it', 'y'];
regions['B'] = ['I', 'like', 'bananas'];
var selRegion = document.getElementById('region');
selRegion.onchange = setMunicipalities;
var selMun = document.getElementById('municipality');
function setMunicipalities(e)
{
while(selMun.length > 0)
{
selMun.remove(0);
}
if(selRegion.selectedOptions[0].value === 'ALL')
{
for(var r in regions)
{
if(regions.hasOwnProperty(r))
{
addMunicipalities(regions[r]);
}
}
}
else
{
var reg = selRegion.selectedOptions[0].value;
addMunicipalities(regions[reg]);
}
}
function addMunicipalities(region)
{
var allMun = document.createElement('option');
allMun.setAttribute('value', 'ALL');
var allMunText = document.createTextNode('ALL');
allMun.appendChild(allMunText);
selMun.add(allMun);
for (var mi = 0; mi < region.length; mi++)
{
var m = region[mi];
var mun = document.createElement('option');
mun.setAttribute('value', m);
var munText = document.createTextNode(m);
mun.appendChild(munText);
selMun.add(mun);
}
}
setMunicipalities(null);
<label for="region">Region</label>
<select id="region">
<option selected="selected" value="ALL">ALL</option>
<option value="A">A</option>
<option value="B">B</option>
</select>
<label for="municipality">Municipality</label>
<select id="municipality">
</select>
I haven't read your entire code because I had a hard time reading code with contents not in English but anyway, I get what you're trying to do here. Suppose that your first select list contains "Region A" and "Region B" as options; "Municipality A1", "Municipality A2", "Municipality B1","Municipality B2" are the possible options for the second select list. Here's a function that will change the options of the second select list depending on what is selected on the first select list:
function optionChanger(v_selected){
var whatisselected= v_selected.options[v_selected.selectedIndex].value;
var municipalities= {};
municipalities['A'] = ['Municipality A1','Municipality A2'];
municipalities['B'] = ['Municipality B1','Municipality B2'];
v_selected.options.length=0; //remove the contents of the second select list
v_selected.options[0] = new Option(municipalities[whatisselected][0],municipalities[whatisselected][0],false,true);// set the first option of the second list as the default selected value
for(x=1;x<municipalities[whatisselected].length;x++){ //add the remaining options to the second list
v_selected.options[x] = new Option(municipalities[whatisselected][x],municipalities[whatisselected][x],false,false);
}
}
Then add this inside the tag of your FIRST select list:
onchange='optionChanger(this)'
PS: Please notice that the return value of the first select list must be 'A', 'B'