Filling a dropdown list based on another dropdown list in the same html form
I have an HTML form with a bunch of options inside and I'd like to change the values inside those options based on previous user selection:
Let's say I have something like this:
<select name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="peach">Peach</option>
</select>
Based on what the user select there I'd like to have another dropdown list after this one displaying differents values. Something like this if the user select "Apple" in the first dropdown list:
<select name="price">
<option value="3">Apple 1kg 3€</option>
<option value="5">Apple 2kg 5€</option>
<option value="7">Apple 3kg 7€</option>
</select>
Something like this if he select "Banana":
<select name="price">
<option value="4">Banana 1kg 4€</option>
<option value="7">Banana 2kg 7€</option>
<option value="10">Banana 3kg 10€</option>
</select>
The value and the text need to change based on the first dropdown list because bananas have a different price than apples and so on. I read a few threads about it but I wasn't really able to understand what I need to make this happen. I never touched ajax before and from what I can read here: Changing value of droplist based on the value of another dropdown list I need some basic stuff about it. Is it possible to do it just using JavaScript?
javascript html list dropdown
|
show 1 more comment
I have an HTML form with a bunch of options inside and I'd like to change the values inside those options based on previous user selection:
Let's say I have something like this:
<select name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="peach">Peach</option>
</select>
Based on what the user select there I'd like to have another dropdown list after this one displaying differents values. Something like this if the user select "Apple" in the first dropdown list:
<select name="price">
<option value="3">Apple 1kg 3€</option>
<option value="5">Apple 2kg 5€</option>
<option value="7">Apple 3kg 7€</option>
</select>
Something like this if he select "Banana":
<select name="price">
<option value="4">Banana 1kg 4€</option>
<option value="7">Banana 2kg 7€</option>
<option value="10">Banana 3kg 10€</option>
</select>
The value and the text need to change based on the first dropdown list because bananas have a different price than apples and so on. I read a few threads about it but I wasn't really able to understand what I need to make this happen. I never touched ajax before and from what I can read here: Changing value of droplist based on the value of another dropdown list I need some basic stuff about it. Is it possible to do it just using JavaScript?
javascript html list dropdown
You don't need AJAX for this, but yes, you need JavaScript to detect a change on your first dropdown to fill the second dropdown.
– bart
Nov 21 '18 at 10:34
There are several way you can achieve this using only Js, one way, you can create all the possible price lists, make them all undisplayed, and only shows one of them according to fruit selection. Another way maybe, is to keep the price list empty, and just fill it with values only upon user’s fruit selection. Try those options and post back if you struggle with coding them.
– Ahmed Hammad
Nov 21 '18 at 10:35
But first, you'll have to defined your pricing for each option, in a JavaScript object or array.
– bart
Nov 21 '18 at 10:36
First question: Where do you get the prices from?
– yunzen
Nov 21 '18 at 10:40
@HerrSerker I just started coding so I am completly unaware of how to do this. I'm assuming your question is to know if I have a DB or not. No I don't right now but I could make it based on your answers to the question. Since I'd like to learn, let's say I have a database with those values inside:id_fruit fruit_name price_1kg price_2kg price_3kg
– TheNoobUser
Nov 21 '18 at 10:45
|
show 1 more comment
I have an HTML form with a bunch of options inside and I'd like to change the values inside those options based on previous user selection:
Let's say I have something like this:
<select name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="peach">Peach</option>
</select>
Based on what the user select there I'd like to have another dropdown list after this one displaying differents values. Something like this if the user select "Apple" in the first dropdown list:
<select name="price">
<option value="3">Apple 1kg 3€</option>
<option value="5">Apple 2kg 5€</option>
<option value="7">Apple 3kg 7€</option>
</select>
Something like this if he select "Banana":
<select name="price">
<option value="4">Banana 1kg 4€</option>
<option value="7">Banana 2kg 7€</option>
<option value="10">Banana 3kg 10€</option>
</select>
The value and the text need to change based on the first dropdown list because bananas have a different price than apples and so on. I read a few threads about it but I wasn't really able to understand what I need to make this happen. I never touched ajax before and from what I can read here: Changing value of droplist based on the value of another dropdown list I need some basic stuff about it. Is it possible to do it just using JavaScript?
javascript html list dropdown
I have an HTML form with a bunch of options inside and I'd like to change the values inside those options based on previous user selection:
Let's say I have something like this:
<select name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="peach">Peach</option>
</select>
Based on what the user select there I'd like to have another dropdown list after this one displaying differents values. Something like this if the user select "Apple" in the first dropdown list:
<select name="price">
<option value="3">Apple 1kg 3€</option>
<option value="5">Apple 2kg 5€</option>
<option value="7">Apple 3kg 7€</option>
</select>
Something like this if he select "Banana":
<select name="price">
<option value="4">Banana 1kg 4€</option>
<option value="7">Banana 2kg 7€</option>
<option value="10">Banana 3kg 10€</option>
</select>
The value and the text need to change based on the first dropdown list because bananas have a different price than apples and so on. I read a few threads about it but I wasn't really able to understand what I need to make this happen. I never touched ajax before and from what I can read here: Changing value of droplist based on the value of another dropdown list I need some basic stuff about it. Is it possible to do it just using JavaScript?
javascript html list dropdown
javascript html list dropdown
edited Nov 21 '18 at 11:23
Shabeer Sha
61110
61110
asked Nov 21 '18 at 10:30
TheNoobUserTheNoobUser
769
769
You don't need AJAX for this, but yes, you need JavaScript to detect a change on your first dropdown to fill the second dropdown.
– bart
Nov 21 '18 at 10:34
There are several way you can achieve this using only Js, one way, you can create all the possible price lists, make them all undisplayed, and only shows one of them according to fruit selection. Another way maybe, is to keep the price list empty, and just fill it with values only upon user’s fruit selection. Try those options and post back if you struggle with coding them.
– Ahmed Hammad
Nov 21 '18 at 10:35
But first, you'll have to defined your pricing for each option, in a JavaScript object or array.
– bart
Nov 21 '18 at 10:36
First question: Where do you get the prices from?
– yunzen
Nov 21 '18 at 10:40
@HerrSerker I just started coding so I am completly unaware of how to do this. I'm assuming your question is to know if I have a DB or not. No I don't right now but I could make it based on your answers to the question. Since I'd like to learn, let's say I have a database with those values inside:id_fruit fruit_name price_1kg price_2kg price_3kg
– TheNoobUser
Nov 21 '18 at 10:45
|
show 1 more comment
You don't need AJAX for this, but yes, you need JavaScript to detect a change on your first dropdown to fill the second dropdown.
– bart
Nov 21 '18 at 10:34
There are several way you can achieve this using only Js, one way, you can create all the possible price lists, make them all undisplayed, and only shows one of them according to fruit selection. Another way maybe, is to keep the price list empty, and just fill it with values only upon user’s fruit selection. Try those options and post back if you struggle with coding them.
– Ahmed Hammad
Nov 21 '18 at 10:35
But first, you'll have to defined your pricing for each option, in a JavaScript object or array.
– bart
Nov 21 '18 at 10:36
First question: Where do you get the prices from?
– yunzen
Nov 21 '18 at 10:40
@HerrSerker I just started coding so I am completly unaware of how to do this. I'm assuming your question is to know if I have a DB or not. No I don't right now but I could make it based on your answers to the question. Since I'd like to learn, let's say I have a database with those values inside:id_fruit fruit_name price_1kg price_2kg price_3kg
– TheNoobUser
Nov 21 '18 at 10:45
You don't need AJAX for this, but yes, you need JavaScript to detect a change on your first dropdown to fill the second dropdown.
– bart
Nov 21 '18 at 10:34
You don't need AJAX for this, but yes, you need JavaScript to detect a change on your first dropdown to fill the second dropdown.
– bart
Nov 21 '18 at 10:34
There are several way you can achieve this using only Js, one way, you can create all the possible price lists, make them all undisplayed, and only shows one of them according to fruit selection. Another way maybe, is to keep the price list empty, and just fill it with values only upon user’s fruit selection. Try those options and post back if you struggle with coding them.
– Ahmed Hammad
Nov 21 '18 at 10:35
There are several way you can achieve this using only Js, one way, you can create all the possible price lists, make them all undisplayed, and only shows one of them according to fruit selection. Another way maybe, is to keep the price list empty, and just fill it with values only upon user’s fruit selection. Try those options and post back if you struggle with coding them.
– Ahmed Hammad
Nov 21 '18 at 10:35
But first, you'll have to defined your pricing for each option, in a JavaScript object or array.
– bart
Nov 21 '18 at 10:36
But first, you'll have to defined your pricing for each option, in a JavaScript object or array.
– bart
Nov 21 '18 at 10:36
First question: Where do you get the prices from?
– yunzen
Nov 21 '18 at 10:40
First question: Where do you get the prices from?
– yunzen
Nov 21 '18 at 10:40
@HerrSerker I just started coding so I am completly unaware of how to do this. I'm assuming your question is to know if I have a DB or not. No I don't right now but I could make it based on your answers to the question. Since I'd like to learn, let's say I have a database with those values inside:
id_fruit fruit_name price_1kg price_2kg price_3kg
– TheNoobUser
Nov 21 '18 at 10:45
@HerrSerker I just started coding so I am completly unaware of how to do this. I'm assuming your question is to know if I have a DB or not. No I don't right now but I could make it based on your answers to the question. Since I'd like to learn, let's say I have a database with those values inside:
id_fruit fruit_name price_1kg price_2kg price_3kg
– TheNoobUser
Nov 21 '18 at 10:45
|
show 1 more comment
3 Answers
3
active
oldest
votes
You can achieve this using an object to hold the values and there associated dropdowns descriptions. In order to do this, your firstly need to add an eventListener
to your dropdown so that it will detect a change when you pick a new fruit. Using this event listener, you can retrieve the value of the option which was selected using this.value
.
Using the value
from the option selected you can proceed to get its associated drop-down values from the object called prices
(this will return an array). Once you've got this array, you can loop through it and "build" a string of HTML using .reduce()
to place as the options for the price
select tag. Once you've built this string, you can append it inside the select tag using .innerHTML
which "converts" your HTML string to DOM objects (real elements rather than just text):
let prices = {"apple":[{value:3,desc:"Apple 1kg 3€"},{value:5,desc:"Apple 2kg 5€"},{value:7,desc:"Apple 3kg 7€"}],
"banana":[{value:3,desc:"Banana 2kg 3.5€"},{value:5,desc:"Banana 4kg 7€"},{value:7,desc:"Banana 5kg 11€"}],
"peach":[{value:3,desc:"Peach 1.5kg 3€"},{value:5,desc:"Peach 3kg 6€"},{value:7,desc:"Peach 4kg 7€"}]}
document.getElementsByName('fruit')[0].addEventListener('change', function(e) {
document.getElementsByName('price')[0].innerHTML = prices[this.value].reduce((acc, elem) => `${acc}<option value="${elem.value}">${elem.desc}</option>`, "");
});
<select name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="peach">Peach</option>
</select>
<br />
<select name="price">
<option value="3">Apple 1kg 3€</option>
<option value="5">Apple 2kg 5€</option>
<option value="7">Apple 3kg 7€</option>
</select>
If you don't feel comfortable using .reduce()
you can use a regular for loop instead:
document.getElementsByName('fruit')[0].addEventListener('change', function(e) {
let options = "";
for(obj of prices[this.value]) {
options += '<option value="' +obj.value +'">' +obj.desc +'</option>';
}
document.getElementsByName('price')[0].innerHTML = options;
});
I think I got what you are saying, however is not fully working for me, probably I have done something wrong (I'm sure I have done something wrong). Could you please post a full example of it? Including thescript
tag? This is my very first attemp with js. Only used php/sql since today
– TheNoobUser
Nov 21 '18 at 11:33
@TheNoobUser Yeah, no worries. One sec...
– Nick Parsons
Nov 21 '18 at 11:34
1
@TheNoobUser jsfiddle.net/jng3a0mh <--- Notice the position of the scrit tags
– Nick Parsons
Nov 21 '18 at 11:40
1
Parson Thank you so much. I got my mistake now, I was adding the script before the actual list. Now it works and I will have to read more about js. Thanks a lot and have a nice day
– TheNoobUser
Nov 21 '18 at 11:44
1
No worries, the reason as to why it wasn't working was because the javascript was running before the entire page had loaded. This means that when the javascript doesdocument.getElementsByName('fruit')
it can't find the element with the namefruit
as it hasn't loaded in yet. So, we can fix this by putting the javascript at the bottom of the page so everything is loaded before we get to the javascrit or we can use the.onload
event, which will fire the javascript once the entire page has loaded.
– Nick Parsons
Nov 21 '18 at 11:47
|
show 1 more comment
Here is an attached solution using element creation and onchange event with JQuery
// First we initialize a variable with the fruits and their prices per kg
fruitPrices = {'apple':[3, 5, 6], 'banana':[4, 7, 10]}
// Listen to changes in selected fruit
$('#fruit-selector').on('change', function(element) {
// Clearing the price selector and getting the selected fruit
$('#price-selector').empty()
chosenFruit = this.value;
// For each price in the fruitPrices for this fruit
for (fruitIndex in fruitPrices[chosenFruit]) {
// Get the price and create an option element for it
price = fruitPrices[chosenFruit][fruitIndex];
price_option = '<option>{0} {1}kg {2}$<option>'.replace('{0}', chosenFruit).replace('{1}', fruitIndex + 1).replace('{2}', price);
// Add the option to the price selector
$('#price-selector').append(price_option)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='fruit-selector' name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="peach">Peach</option>
</select>
<select id='price-selector' name="price">
</select>
add a comment |
console.clear();
(function() {
var fruitsField = document.querySelector('[name=fruits]')
var amountField = document.querySelector('[name=amount]')
var json = {};
onReady(loadJson);
fruitsField.addEventListener('change', populateAmount)
function onReady(callback) {
if (
document.readyState === "complete" ||
(document.readyState !== "loading" && !document.documentElement.doScroll)
) {
callback();
} else {
document.addEventListener("DOMContentLoaded", callback);
}
}
function getSelectedFruit() {
return fruitsField.value;
}
function populateFruits() {
clearOptions(fruitsField)
fruits = json.fruits
for (var i in fruits) {
addOption(fruitsField, i, fruits[i])
}
}
function populateAmount() {
clearOptions(amountField)
var fruit = getSelectedFruit()
fruits = json.fruits
prices = json.prices[fruit]
for (var i in prices) {
addOption(amountField, i, fruits[fruit] + " " + i + "kg " + prices[i] + "€")
}
}
// Load a json resource and start the fruit process
function loadJson() {
fetch('//api.jsonbin.io/b/5bf5645b746e9b593ec0e8b5')
.then(function(response) {
return response.json()
})
.then(function(response) {
json = response
populateFruits()
})
.catch(function(err) {
console.error(err);
})
}
// function loadJson() {
// var j = '{"fruits":{"apple":"Apples","banana":"Bananas","peach":"Peaches"},"prices":{"apple":{"1":3,"2":5,"3":7},"banana":{"1":4,"2":7,"3":10},"peach":{"1":5,"2":9,"3":13}}}'
// json = JSON.parse(j)
// populateFruits()
// }
function addOption(select, value, text) {
var option = document.createElement('option')
option.setAttribute('value', value)
option.textContent = text
select.appendChild(option)
}
function clearOptions(select) {
var children = select.children
var childrenToRemove = ;
for (var i = 1; i < children.length; i++) {
childrenToRemove.push(children[i])
}
for (var i = 0; i < childrenToRemove.length; i++) {
select.removeChild(childrenToRemove[i])
}
}
}())
<form>
<select name="fruits" size="4">
<option value="0">Select Fruit</option>
</select>
<select name="amount" size="4">
<option value="0" >Select Amount</option>
</select>
</form>
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53410084%2ffilling-a-dropdown-list-based-on-another-dropdown-list-in-the-same-html-form%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can achieve this using an object to hold the values and there associated dropdowns descriptions. In order to do this, your firstly need to add an eventListener
to your dropdown so that it will detect a change when you pick a new fruit. Using this event listener, you can retrieve the value of the option which was selected using this.value
.
Using the value
from the option selected you can proceed to get its associated drop-down values from the object called prices
(this will return an array). Once you've got this array, you can loop through it and "build" a string of HTML using .reduce()
to place as the options for the price
select tag. Once you've built this string, you can append it inside the select tag using .innerHTML
which "converts" your HTML string to DOM objects (real elements rather than just text):
let prices = {"apple":[{value:3,desc:"Apple 1kg 3€"},{value:5,desc:"Apple 2kg 5€"},{value:7,desc:"Apple 3kg 7€"}],
"banana":[{value:3,desc:"Banana 2kg 3.5€"},{value:5,desc:"Banana 4kg 7€"},{value:7,desc:"Banana 5kg 11€"}],
"peach":[{value:3,desc:"Peach 1.5kg 3€"},{value:5,desc:"Peach 3kg 6€"},{value:7,desc:"Peach 4kg 7€"}]}
document.getElementsByName('fruit')[0].addEventListener('change', function(e) {
document.getElementsByName('price')[0].innerHTML = prices[this.value].reduce((acc, elem) => `${acc}<option value="${elem.value}">${elem.desc}</option>`, "");
});
<select name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="peach">Peach</option>
</select>
<br />
<select name="price">
<option value="3">Apple 1kg 3€</option>
<option value="5">Apple 2kg 5€</option>
<option value="7">Apple 3kg 7€</option>
</select>
If you don't feel comfortable using .reduce()
you can use a regular for loop instead:
document.getElementsByName('fruit')[0].addEventListener('change', function(e) {
let options = "";
for(obj of prices[this.value]) {
options += '<option value="' +obj.value +'">' +obj.desc +'</option>';
}
document.getElementsByName('price')[0].innerHTML = options;
});
I think I got what you are saying, however is not fully working for me, probably I have done something wrong (I'm sure I have done something wrong). Could you please post a full example of it? Including thescript
tag? This is my very first attemp with js. Only used php/sql since today
– TheNoobUser
Nov 21 '18 at 11:33
@TheNoobUser Yeah, no worries. One sec...
– Nick Parsons
Nov 21 '18 at 11:34
1
@TheNoobUser jsfiddle.net/jng3a0mh <--- Notice the position of the scrit tags
– Nick Parsons
Nov 21 '18 at 11:40
1
Parson Thank you so much. I got my mistake now, I was adding the script before the actual list. Now it works and I will have to read more about js. Thanks a lot and have a nice day
– TheNoobUser
Nov 21 '18 at 11:44
1
No worries, the reason as to why it wasn't working was because the javascript was running before the entire page had loaded. This means that when the javascript doesdocument.getElementsByName('fruit')
it can't find the element with the namefruit
as it hasn't loaded in yet. So, we can fix this by putting the javascript at the bottom of the page so everything is loaded before we get to the javascrit or we can use the.onload
event, which will fire the javascript once the entire page has loaded.
– Nick Parsons
Nov 21 '18 at 11:47
|
show 1 more comment
You can achieve this using an object to hold the values and there associated dropdowns descriptions. In order to do this, your firstly need to add an eventListener
to your dropdown so that it will detect a change when you pick a new fruit. Using this event listener, you can retrieve the value of the option which was selected using this.value
.
Using the value
from the option selected you can proceed to get its associated drop-down values from the object called prices
(this will return an array). Once you've got this array, you can loop through it and "build" a string of HTML using .reduce()
to place as the options for the price
select tag. Once you've built this string, you can append it inside the select tag using .innerHTML
which "converts" your HTML string to DOM objects (real elements rather than just text):
let prices = {"apple":[{value:3,desc:"Apple 1kg 3€"},{value:5,desc:"Apple 2kg 5€"},{value:7,desc:"Apple 3kg 7€"}],
"banana":[{value:3,desc:"Banana 2kg 3.5€"},{value:5,desc:"Banana 4kg 7€"},{value:7,desc:"Banana 5kg 11€"}],
"peach":[{value:3,desc:"Peach 1.5kg 3€"},{value:5,desc:"Peach 3kg 6€"},{value:7,desc:"Peach 4kg 7€"}]}
document.getElementsByName('fruit')[0].addEventListener('change', function(e) {
document.getElementsByName('price')[0].innerHTML = prices[this.value].reduce((acc, elem) => `${acc}<option value="${elem.value}">${elem.desc}</option>`, "");
});
<select name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="peach">Peach</option>
</select>
<br />
<select name="price">
<option value="3">Apple 1kg 3€</option>
<option value="5">Apple 2kg 5€</option>
<option value="7">Apple 3kg 7€</option>
</select>
If you don't feel comfortable using .reduce()
you can use a regular for loop instead:
document.getElementsByName('fruit')[0].addEventListener('change', function(e) {
let options = "";
for(obj of prices[this.value]) {
options += '<option value="' +obj.value +'">' +obj.desc +'</option>';
}
document.getElementsByName('price')[0].innerHTML = options;
});
I think I got what you are saying, however is not fully working for me, probably I have done something wrong (I'm sure I have done something wrong). Could you please post a full example of it? Including thescript
tag? This is my very first attemp with js. Only used php/sql since today
– TheNoobUser
Nov 21 '18 at 11:33
@TheNoobUser Yeah, no worries. One sec...
– Nick Parsons
Nov 21 '18 at 11:34
1
@TheNoobUser jsfiddle.net/jng3a0mh <--- Notice the position of the scrit tags
– Nick Parsons
Nov 21 '18 at 11:40
1
Parson Thank you so much. I got my mistake now, I was adding the script before the actual list. Now it works and I will have to read more about js. Thanks a lot and have a nice day
– TheNoobUser
Nov 21 '18 at 11:44
1
No worries, the reason as to why it wasn't working was because the javascript was running before the entire page had loaded. This means that when the javascript doesdocument.getElementsByName('fruit')
it can't find the element with the namefruit
as it hasn't loaded in yet. So, we can fix this by putting the javascript at the bottom of the page so everything is loaded before we get to the javascrit or we can use the.onload
event, which will fire the javascript once the entire page has loaded.
– Nick Parsons
Nov 21 '18 at 11:47
|
show 1 more comment
You can achieve this using an object to hold the values and there associated dropdowns descriptions. In order to do this, your firstly need to add an eventListener
to your dropdown so that it will detect a change when you pick a new fruit. Using this event listener, you can retrieve the value of the option which was selected using this.value
.
Using the value
from the option selected you can proceed to get its associated drop-down values from the object called prices
(this will return an array). Once you've got this array, you can loop through it and "build" a string of HTML using .reduce()
to place as the options for the price
select tag. Once you've built this string, you can append it inside the select tag using .innerHTML
which "converts" your HTML string to DOM objects (real elements rather than just text):
let prices = {"apple":[{value:3,desc:"Apple 1kg 3€"},{value:5,desc:"Apple 2kg 5€"},{value:7,desc:"Apple 3kg 7€"}],
"banana":[{value:3,desc:"Banana 2kg 3.5€"},{value:5,desc:"Banana 4kg 7€"},{value:7,desc:"Banana 5kg 11€"}],
"peach":[{value:3,desc:"Peach 1.5kg 3€"},{value:5,desc:"Peach 3kg 6€"},{value:7,desc:"Peach 4kg 7€"}]}
document.getElementsByName('fruit')[0].addEventListener('change', function(e) {
document.getElementsByName('price')[0].innerHTML = prices[this.value].reduce((acc, elem) => `${acc}<option value="${elem.value}">${elem.desc}</option>`, "");
});
<select name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="peach">Peach</option>
</select>
<br />
<select name="price">
<option value="3">Apple 1kg 3€</option>
<option value="5">Apple 2kg 5€</option>
<option value="7">Apple 3kg 7€</option>
</select>
If you don't feel comfortable using .reduce()
you can use a regular for loop instead:
document.getElementsByName('fruit')[0].addEventListener('change', function(e) {
let options = "";
for(obj of prices[this.value]) {
options += '<option value="' +obj.value +'">' +obj.desc +'</option>';
}
document.getElementsByName('price')[0].innerHTML = options;
});
You can achieve this using an object to hold the values and there associated dropdowns descriptions. In order to do this, your firstly need to add an eventListener
to your dropdown so that it will detect a change when you pick a new fruit. Using this event listener, you can retrieve the value of the option which was selected using this.value
.
Using the value
from the option selected you can proceed to get its associated drop-down values from the object called prices
(this will return an array). Once you've got this array, you can loop through it and "build" a string of HTML using .reduce()
to place as the options for the price
select tag. Once you've built this string, you can append it inside the select tag using .innerHTML
which "converts" your HTML string to DOM objects (real elements rather than just text):
let prices = {"apple":[{value:3,desc:"Apple 1kg 3€"},{value:5,desc:"Apple 2kg 5€"},{value:7,desc:"Apple 3kg 7€"}],
"banana":[{value:3,desc:"Banana 2kg 3.5€"},{value:5,desc:"Banana 4kg 7€"},{value:7,desc:"Banana 5kg 11€"}],
"peach":[{value:3,desc:"Peach 1.5kg 3€"},{value:5,desc:"Peach 3kg 6€"},{value:7,desc:"Peach 4kg 7€"}]}
document.getElementsByName('fruit')[0].addEventListener('change', function(e) {
document.getElementsByName('price')[0].innerHTML = prices[this.value].reduce((acc, elem) => `${acc}<option value="${elem.value}">${elem.desc}</option>`, "");
});
<select name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="peach">Peach</option>
</select>
<br />
<select name="price">
<option value="3">Apple 1kg 3€</option>
<option value="5">Apple 2kg 5€</option>
<option value="7">Apple 3kg 7€</option>
</select>
If you don't feel comfortable using .reduce()
you can use a regular for loop instead:
document.getElementsByName('fruit')[0].addEventListener('change', function(e) {
let options = "";
for(obj of prices[this.value]) {
options += '<option value="' +obj.value +'">' +obj.desc +'</option>';
}
document.getElementsByName('price')[0].innerHTML = options;
});
let prices = {"apple":[{value:3,desc:"Apple 1kg 3€"},{value:5,desc:"Apple 2kg 5€"},{value:7,desc:"Apple 3kg 7€"}],
"banana":[{value:3,desc:"Banana 2kg 3.5€"},{value:5,desc:"Banana 4kg 7€"},{value:7,desc:"Banana 5kg 11€"}],
"peach":[{value:3,desc:"Peach 1.5kg 3€"},{value:5,desc:"Peach 3kg 6€"},{value:7,desc:"Peach 4kg 7€"}]}
document.getElementsByName('fruit')[0].addEventListener('change', function(e) {
document.getElementsByName('price')[0].innerHTML = prices[this.value].reduce((acc, elem) => `${acc}<option value="${elem.value}">${elem.desc}</option>`, "");
});
<select name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="peach">Peach</option>
</select>
<br />
<select name="price">
<option value="3">Apple 1kg 3€</option>
<option value="5">Apple 2kg 5€</option>
<option value="7">Apple 3kg 7€</option>
</select>
let prices = {"apple":[{value:3,desc:"Apple 1kg 3€"},{value:5,desc:"Apple 2kg 5€"},{value:7,desc:"Apple 3kg 7€"}],
"banana":[{value:3,desc:"Banana 2kg 3.5€"},{value:5,desc:"Banana 4kg 7€"},{value:7,desc:"Banana 5kg 11€"}],
"peach":[{value:3,desc:"Peach 1.5kg 3€"},{value:5,desc:"Peach 3kg 6€"},{value:7,desc:"Peach 4kg 7€"}]}
document.getElementsByName('fruit')[0].addEventListener('change', function(e) {
document.getElementsByName('price')[0].innerHTML = prices[this.value].reduce((acc, elem) => `${acc}<option value="${elem.value}">${elem.desc}</option>`, "");
});
<select name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="peach">Peach</option>
</select>
<br />
<select name="price">
<option value="3">Apple 1kg 3€</option>
<option value="5">Apple 2kg 5€</option>
<option value="7">Apple 3kg 7€</option>
</select>
edited Nov 21 '18 at 11:33
answered Nov 21 '18 at 11:05
Nick ParsonsNick Parsons
7,3102724
7,3102724
I think I got what you are saying, however is not fully working for me, probably I have done something wrong (I'm sure I have done something wrong). Could you please post a full example of it? Including thescript
tag? This is my very first attemp with js. Only used php/sql since today
– TheNoobUser
Nov 21 '18 at 11:33
@TheNoobUser Yeah, no worries. One sec...
– Nick Parsons
Nov 21 '18 at 11:34
1
@TheNoobUser jsfiddle.net/jng3a0mh <--- Notice the position of the scrit tags
– Nick Parsons
Nov 21 '18 at 11:40
1
Parson Thank you so much. I got my mistake now, I was adding the script before the actual list. Now it works and I will have to read more about js. Thanks a lot and have a nice day
– TheNoobUser
Nov 21 '18 at 11:44
1
No worries, the reason as to why it wasn't working was because the javascript was running before the entire page had loaded. This means that when the javascript doesdocument.getElementsByName('fruit')
it can't find the element with the namefruit
as it hasn't loaded in yet. So, we can fix this by putting the javascript at the bottom of the page so everything is loaded before we get to the javascrit or we can use the.onload
event, which will fire the javascript once the entire page has loaded.
– Nick Parsons
Nov 21 '18 at 11:47
|
show 1 more comment
I think I got what you are saying, however is not fully working for me, probably I have done something wrong (I'm sure I have done something wrong). Could you please post a full example of it? Including thescript
tag? This is my very first attemp with js. Only used php/sql since today
– TheNoobUser
Nov 21 '18 at 11:33
@TheNoobUser Yeah, no worries. One sec...
– Nick Parsons
Nov 21 '18 at 11:34
1
@TheNoobUser jsfiddle.net/jng3a0mh <--- Notice the position of the scrit tags
– Nick Parsons
Nov 21 '18 at 11:40
1
Parson Thank you so much. I got my mistake now, I was adding the script before the actual list. Now it works and I will have to read more about js. Thanks a lot and have a nice day
– TheNoobUser
Nov 21 '18 at 11:44
1
No worries, the reason as to why it wasn't working was because the javascript was running before the entire page had loaded. This means that when the javascript doesdocument.getElementsByName('fruit')
it can't find the element with the namefruit
as it hasn't loaded in yet. So, we can fix this by putting the javascript at the bottom of the page so everything is loaded before we get to the javascrit or we can use the.onload
event, which will fire the javascript once the entire page has loaded.
– Nick Parsons
Nov 21 '18 at 11:47
I think I got what you are saying, however is not fully working for me, probably I have done something wrong (I'm sure I have done something wrong). Could you please post a full example of it? Including the
script
tag? This is my very first attemp with js. Only used php/sql since today– TheNoobUser
Nov 21 '18 at 11:33
I think I got what you are saying, however is not fully working for me, probably I have done something wrong (I'm sure I have done something wrong). Could you please post a full example of it? Including the
script
tag? This is my very first attemp with js. Only used php/sql since today– TheNoobUser
Nov 21 '18 at 11:33
@TheNoobUser Yeah, no worries. One sec...
– Nick Parsons
Nov 21 '18 at 11:34
@TheNoobUser Yeah, no worries. One sec...
– Nick Parsons
Nov 21 '18 at 11:34
1
1
@TheNoobUser jsfiddle.net/jng3a0mh <--- Notice the position of the scrit tags
– Nick Parsons
Nov 21 '18 at 11:40
@TheNoobUser jsfiddle.net/jng3a0mh <--- Notice the position of the scrit tags
– Nick Parsons
Nov 21 '18 at 11:40
1
1
Parson Thank you so much. I got my mistake now, I was adding the script before the actual list. Now it works and I will have to read more about js. Thanks a lot and have a nice day
– TheNoobUser
Nov 21 '18 at 11:44
Parson Thank you so much. I got my mistake now, I was adding the script before the actual list. Now it works and I will have to read more about js. Thanks a lot and have a nice day
– TheNoobUser
Nov 21 '18 at 11:44
1
1
No worries, the reason as to why it wasn't working was because the javascript was running before the entire page had loaded. This means that when the javascript does
document.getElementsByName('fruit')
it can't find the element with the name fruit
as it hasn't loaded in yet. So, we can fix this by putting the javascript at the bottom of the page so everything is loaded before we get to the javascrit or we can use the .onload
event, which will fire the javascript once the entire page has loaded.– Nick Parsons
Nov 21 '18 at 11:47
No worries, the reason as to why it wasn't working was because the javascript was running before the entire page had loaded. This means that when the javascript does
document.getElementsByName('fruit')
it can't find the element with the name fruit
as it hasn't loaded in yet. So, we can fix this by putting the javascript at the bottom of the page so everything is loaded before we get to the javascrit or we can use the .onload
event, which will fire the javascript once the entire page has loaded.– Nick Parsons
Nov 21 '18 at 11:47
|
show 1 more comment
Here is an attached solution using element creation and onchange event with JQuery
// First we initialize a variable with the fruits and their prices per kg
fruitPrices = {'apple':[3, 5, 6], 'banana':[4, 7, 10]}
// Listen to changes in selected fruit
$('#fruit-selector').on('change', function(element) {
// Clearing the price selector and getting the selected fruit
$('#price-selector').empty()
chosenFruit = this.value;
// For each price in the fruitPrices for this fruit
for (fruitIndex in fruitPrices[chosenFruit]) {
// Get the price and create an option element for it
price = fruitPrices[chosenFruit][fruitIndex];
price_option = '<option>{0} {1}kg {2}$<option>'.replace('{0}', chosenFruit).replace('{1}', fruitIndex + 1).replace('{2}', price);
// Add the option to the price selector
$('#price-selector').append(price_option)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='fruit-selector' name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="peach">Peach</option>
</select>
<select id='price-selector' name="price">
</select>
add a comment |
Here is an attached solution using element creation and onchange event with JQuery
// First we initialize a variable with the fruits and their prices per kg
fruitPrices = {'apple':[3, 5, 6], 'banana':[4, 7, 10]}
// Listen to changes in selected fruit
$('#fruit-selector').on('change', function(element) {
// Clearing the price selector and getting the selected fruit
$('#price-selector').empty()
chosenFruit = this.value;
// For each price in the fruitPrices for this fruit
for (fruitIndex in fruitPrices[chosenFruit]) {
// Get the price and create an option element for it
price = fruitPrices[chosenFruit][fruitIndex];
price_option = '<option>{0} {1}kg {2}$<option>'.replace('{0}', chosenFruit).replace('{1}', fruitIndex + 1).replace('{2}', price);
// Add the option to the price selector
$('#price-selector').append(price_option)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='fruit-selector' name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="peach">Peach</option>
</select>
<select id='price-selector' name="price">
</select>
add a comment |
Here is an attached solution using element creation and onchange event with JQuery
// First we initialize a variable with the fruits and their prices per kg
fruitPrices = {'apple':[3, 5, 6], 'banana':[4, 7, 10]}
// Listen to changes in selected fruit
$('#fruit-selector').on('change', function(element) {
// Clearing the price selector and getting the selected fruit
$('#price-selector').empty()
chosenFruit = this.value;
// For each price in the fruitPrices for this fruit
for (fruitIndex in fruitPrices[chosenFruit]) {
// Get the price and create an option element for it
price = fruitPrices[chosenFruit][fruitIndex];
price_option = '<option>{0} {1}kg {2}$<option>'.replace('{0}', chosenFruit).replace('{1}', fruitIndex + 1).replace('{2}', price);
// Add the option to the price selector
$('#price-selector').append(price_option)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='fruit-selector' name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="peach">Peach</option>
</select>
<select id='price-selector' name="price">
</select>
Here is an attached solution using element creation and onchange event with JQuery
// First we initialize a variable with the fruits and their prices per kg
fruitPrices = {'apple':[3, 5, 6], 'banana':[4, 7, 10]}
// Listen to changes in selected fruit
$('#fruit-selector').on('change', function(element) {
// Clearing the price selector and getting the selected fruit
$('#price-selector').empty()
chosenFruit = this.value;
// For each price in the fruitPrices for this fruit
for (fruitIndex in fruitPrices[chosenFruit]) {
// Get the price and create an option element for it
price = fruitPrices[chosenFruit][fruitIndex];
price_option = '<option>{0} {1}kg {2}$<option>'.replace('{0}', chosenFruit).replace('{1}', fruitIndex + 1).replace('{2}', price);
// Add the option to the price selector
$('#price-selector').append(price_option)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='fruit-selector' name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="peach">Peach</option>
</select>
<select id='price-selector' name="price">
</select>
// First we initialize a variable with the fruits and their prices per kg
fruitPrices = {'apple':[3, 5, 6], 'banana':[4, 7, 10]}
// Listen to changes in selected fruit
$('#fruit-selector').on('change', function(element) {
// Clearing the price selector and getting the selected fruit
$('#price-selector').empty()
chosenFruit = this.value;
// For each price in the fruitPrices for this fruit
for (fruitIndex in fruitPrices[chosenFruit]) {
// Get the price and create an option element for it
price = fruitPrices[chosenFruit][fruitIndex];
price_option = '<option>{0} {1}kg {2}$<option>'.replace('{0}', chosenFruit).replace('{1}', fruitIndex + 1).replace('{2}', price);
// Add the option to the price selector
$('#price-selector').append(price_option)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='fruit-selector' name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="peach">Peach</option>
</select>
<select id='price-selector' name="price">
</select>
// First we initialize a variable with the fruits and their prices per kg
fruitPrices = {'apple':[3, 5, 6], 'banana':[4, 7, 10]}
// Listen to changes in selected fruit
$('#fruit-selector').on('change', function(element) {
// Clearing the price selector and getting the selected fruit
$('#price-selector').empty()
chosenFruit = this.value;
// For each price in the fruitPrices for this fruit
for (fruitIndex in fruitPrices[chosenFruit]) {
// Get the price and create an option element for it
price = fruitPrices[chosenFruit][fruitIndex];
price_option = '<option>{0} {1}kg {2}$<option>'.replace('{0}', chosenFruit).replace('{1}', fruitIndex + 1).replace('{2}', price);
// Add the option to the price selector
$('#price-selector').append(price_option)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='fruit-selector' name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="peach">Peach</option>
</select>
<select id='price-selector' name="price">
</select>
answered Nov 21 '18 at 11:05
ShushanShushan
1,1171814
1,1171814
add a comment |
add a comment |
console.clear();
(function() {
var fruitsField = document.querySelector('[name=fruits]')
var amountField = document.querySelector('[name=amount]')
var json = {};
onReady(loadJson);
fruitsField.addEventListener('change', populateAmount)
function onReady(callback) {
if (
document.readyState === "complete" ||
(document.readyState !== "loading" && !document.documentElement.doScroll)
) {
callback();
} else {
document.addEventListener("DOMContentLoaded", callback);
}
}
function getSelectedFruit() {
return fruitsField.value;
}
function populateFruits() {
clearOptions(fruitsField)
fruits = json.fruits
for (var i in fruits) {
addOption(fruitsField, i, fruits[i])
}
}
function populateAmount() {
clearOptions(amountField)
var fruit = getSelectedFruit()
fruits = json.fruits
prices = json.prices[fruit]
for (var i in prices) {
addOption(amountField, i, fruits[fruit] + " " + i + "kg " + prices[i] + "€")
}
}
// Load a json resource and start the fruit process
function loadJson() {
fetch('//api.jsonbin.io/b/5bf5645b746e9b593ec0e8b5')
.then(function(response) {
return response.json()
})
.then(function(response) {
json = response
populateFruits()
})
.catch(function(err) {
console.error(err);
})
}
// function loadJson() {
// var j = '{"fruits":{"apple":"Apples","banana":"Bananas","peach":"Peaches"},"prices":{"apple":{"1":3,"2":5,"3":7},"banana":{"1":4,"2":7,"3":10},"peach":{"1":5,"2":9,"3":13}}}'
// json = JSON.parse(j)
// populateFruits()
// }
function addOption(select, value, text) {
var option = document.createElement('option')
option.setAttribute('value', value)
option.textContent = text
select.appendChild(option)
}
function clearOptions(select) {
var children = select.children
var childrenToRemove = ;
for (var i = 1; i < children.length; i++) {
childrenToRemove.push(children[i])
}
for (var i = 0; i < childrenToRemove.length; i++) {
select.removeChild(childrenToRemove[i])
}
}
}())
<form>
<select name="fruits" size="4">
<option value="0">Select Fruit</option>
</select>
<select name="amount" size="4">
<option value="0" >Select Amount</option>
</select>
</form>
add a comment |
console.clear();
(function() {
var fruitsField = document.querySelector('[name=fruits]')
var amountField = document.querySelector('[name=amount]')
var json = {};
onReady(loadJson);
fruitsField.addEventListener('change', populateAmount)
function onReady(callback) {
if (
document.readyState === "complete" ||
(document.readyState !== "loading" && !document.documentElement.doScroll)
) {
callback();
} else {
document.addEventListener("DOMContentLoaded", callback);
}
}
function getSelectedFruit() {
return fruitsField.value;
}
function populateFruits() {
clearOptions(fruitsField)
fruits = json.fruits
for (var i in fruits) {
addOption(fruitsField, i, fruits[i])
}
}
function populateAmount() {
clearOptions(amountField)
var fruit = getSelectedFruit()
fruits = json.fruits
prices = json.prices[fruit]
for (var i in prices) {
addOption(amountField, i, fruits[fruit] + " " + i + "kg " + prices[i] + "€")
}
}
// Load a json resource and start the fruit process
function loadJson() {
fetch('//api.jsonbin.io/b/5bf5645b746e9b593ec0e8b5')
.then(function(response) {
return response.json()
})
.then(function(response) {
json = response
populateFruits()
})
.catch(function(err) {
console.error(err);
})
}
// function loadJson() {
// var j = '{"fruits":{"apple":"Apples","banana":"Bananas","peach":"Peaches"},"prices":{"apple":{"1":3,"2":5,"3":7},"banana":{"1":4,"2":7,"3":10},"peach":{"1":5,"2":9,"3":13}}}'
// json = JSON.parse(j)
// populateFruits()
// }
function addOption(select, value, text) {
var option = document.createElement('option')
option.setAttribute('value', value)
option.textContent = text
select.appendChild(option)
}
function clearOptions(select) {
var children = select.children
var childrenToRemove = ;
for (var i = 1; i < children.length; i++) {
childrenToRemove.push(children[i])
}
for (var i = 0; i < childrenToRemove.length; i++) {
select.removeChild(childrenToRemove[i])
}
}
}())
<form>
<select name="fruits" size="4">
<option value="0">Select Fruit</option>
</select>
<select name="amount" size="4">
<option value="0" >Select Amount</option>
</select>
</form>
add a comment |
console.clear();
(function() {
var fruitsField = document.querySelector('[name=fruits]')
var amountField = document.querySelector('[name=amount]')
var json = {};
onReady(loadJson);
fruitsField.addEventListener('change', populateAmount)
function onReady(callback) {
if (
document.readyState === "complete" ||
(document.readyState !== "loading" && !document.documentElement.doScroll)
) {
callback();
} else {
document.addEventListener("DOMContentLoaded", callback);
}
}
function getSelectedFruit() {
return fruitsField.value;
}
function populateFruits() {
clearOptions(fruitsField)
fruits = json.fruits
for (var i in fruits) {
addOption(fruitsField, i, fruits[i])
}
}
function populateAmount() {
clearOptions(amountField)
var fruit = getSelectedFruit()
fruits = json.fruits
prices = json.prices[fruit]
for (var i in prices) {
addOption(amountField, i, fruits[fruit] + " " + i + "kg " + prices[i] + "€")
}
}
// Load a json resource and start the fruit process
function loadJson() {
fetch('//api.jsonbin.io/b/5bf5645b746e9b593ec0e8b5')
.then(function(response) {
return response.json()
})
.then(function(response) {
json = response
populateFruits()
})
.catch(function(err) {
console.error(err);
})
}
// function loadJson() {
// var j = '{"fruits":{"apple":"Apples","banana":"Bananas","peach":"Peaches"},"prices":{"apple":{"1":3,"2":5,"3":7},"banana":{"1":4,"2":7,"3":10},"peach":{"1":5,"2":9,"3":13}}}'
// json = JSON.parse(j)
// populateFruits()
// }
function addOption(select, value, text) {
var option = document.createElement('option')
option.setAttribute('value', value)
option.textContent = text
select.appendChild(option)
}
function clearOptions(select) {
var children = select.children
var childrenToRemove = ;
for (var i = 1; i < children.length; i++) {
childrenToRemove.push(children[i])
}
for (var i = 0; i < childrenToRemove.length; i++) {
select.removeChild(childrenToRemove[i])
}
}
}())
<form>
<select name="fruits" size="4">
<option value="0">Select Fruit</option>
</select>
<select name="amount" size="4">
<option value="0" >Select Amount</option>
</select>
</form>
console.clear();
(function() {
var fruitsField = document.querySelector('[name=fruits]')
var amountField = document.querySelector('[name=amount]')
var json = {};
onReady(loadJson);
fruitsField.addEventListener('change', populateAmount)
function onReady(callback) {
if (
document.readyState === "complete" ||
(document.readyState !== "loading" && !document.documentElement.doScroll)
) {
callback();
} else {
document.addEventListener("DOMContentLoaded", callback);
}
}
function getSelectedFruit() {
return fruitsField.value;
}
function populateFruits() {
clearOptions(fruitsField)
fruits = json.fruits
for (var i in fruits) {
addOption(fruitsField, i, fruits[i])
}
}
function populateAmount() {
clearOptions(amountField)
var fruit = getSelectedFruit()
fruits = json.fruits
prices = json.prices[fruit]
for (var i in prices) {
addOption(amountField, i, fruits[fruit] + " " + i + "kg " + prices[i] + "€")
}
}
// Load a json resource and start the fruit process
function loadJson() {
fetch('//api.jsonbin.io/b/5bf5645b746e9b593ec0e8b5')
.then(function(response) {
return response.json()
})
.then(function(response) {
json = response
populateFruits()
})
.catch(function(err) {
console.error(err);
})
}
// function loadJson() {
// var j = '{"fruits":{"apple":"Apples","banana":"Bananas","peach":"Peaches"},"prices":{"apple":{"1":3,"2":5,"3":7},"banana":{"1":4,"2":7,"3":10},"peach":{"1":5,"2":9,"3":13}}}'
// json = JSON.parse(j)
// populateFruits()
// }
function addOption(select, value, text) {
var option = document.createElement('option')
option.setAttribute('value', value)
option.textContent = text
select.appendChild(option)
}
function clearOptions(select) {
var children = select.children
var childrenToRemove = ;
for (var i = 1; i < children.length; i++) {
childrenToRemove.push(children[i])
}
for (var i = 0; i < childrenToRemove.length; i++) {
select.removeChild(childrenToRemove[i])
}
}
}())
<form>
<select name="fruits" size="4">
<option value="0">Select Fruit</option>
</select>
<select name="amount" size="4">
<option value="0" >Select Amount</option>
</select>
</form>
console.clear();
(function() {
var fruitsField = document.querySelector('[name=fruits]')
var amountField = document.querySelector('[name=amount]')
var json = {};
onReady(loadJson);
fruitsField.addEventListener('change', populateAmount)
function onReady(callback) {
if (
document.readyState === "complete" ||
(document.readyState !== "loading" && !document.documentElement.doScroll)
) {
callback();
} else {
document.addEventListener("DOMContentLoaded", callback);
}
}
function getSelectedFruit() {
return fruitsField.value;
}
function populateFruits() {
clearOptions(fruitsField)
fruits = json.fruits
for (var i in fruits) {
addOption(fruitsField, i, fruits[i])
}
}
function populateAmount() {
clearOptions(amountField)
var fruit = getSelectedFruit()
fruits = json.fruits
prices = json.prices[fruit]
for (var i in prices) {
addOption(amountField, i, fruits[fruit] + " " + i + "kg " + prices[i] + "€")
}
}
// Load a json resource and start the fruit process
function loadJson() {
fetch('//api.jsonbin.io/b/5bf5645b746e9b593ec0e8b5')
.then(function(response) {
return response.json()
})
.then(function(response) {
json = response
populateFruits()
})
.catch(function(err) {
console.error(err);
})
}
// function loadJson() {
// var j = '{"fruits":{"apple":"Apples","banana":"Bananas","peach":"Peaches"},"prices":{"apple":{"1":3,"2":5,"3":7},"banana":{"1":4,"2":7,"3":10},"peach":{"1":5,"2":9,"3":13}}}'
// json = JSON.parse(j)
// populateFruits()
// }
function addOption(select, value, text) {
var option = document.createElement('option')
option.setAttribute('value', value)
option.textContent = text
select.appendChild(option)
}
function clearOptions(select) {
var children = select.children
var childrenToRemove = ;
for (var i = 1; i < children.length; i++) {
childrenToRemove.push(children[i])
}
for (var i = 0; i < childrenToRemove.length; i++) {
select.removeChild(childrenToRemove[i])
}
}
}())
<form>
<select name="fruits" size="4">
<option value="0">Select Fruit</option>
</select>
<select name="amount" size="4">
<option value="0" >Select Amount</option>
</select>
</form>
console.clear();
(function() {
var fruitsField = document.querySelector('[name=fruits]')
var amountField = document.querySelector('[name=amount]')
var json = {};
onReady(loadJson);
fruitsField.addEventListener('change', populateAmount)
function onReady(callback) {
if (
document.readyState === "complete" ||
(document.readyState !== "loading" && !document.documentElement.doScroll)
) {
callback();
} else {
document.addEventListener("DOMContentLoaded", callback);
}
}
function getSelectedFruit() {
return fruitsField.value;
}
function populateFruits() {
clearOptions(fruitsField)
fruits = json.fruits
for (var i in fruits) {
addOption(fruitsField, i, fruits[i])
}
}
function populateAmount() {
clearOptions(amountField)
var fruit = getSelectedFruit()
fruits = json.fruits
prices = json.prices[fruit]
for (var i in prices) {
addOption(amountField, i, fruits[fruit] + " " + i + "kg " + prices[i] + "€")
}
}
// Load a json resource and start the fruit process
function loadJson() {
fetch('//api.jsonbin.io/b/5bf5645b746e9b593ec0e8b5')
.then(function(response) {
return response.json()
})
.then(function(response) {
json = response
populateFruits()
})
.catch(function(err) {
console.error(err);
})
}
// function loadJson() {
// var j = '{"fruits":{"apple":"Apples","banana":"Bananas","peach":"Peaches"},"prices":{"apple":{"1":3,"2":5,"3":7},"banana":{"1":4,"2":7,"3":10},"peach":{"1":5,"2":9,"3":13}}}'
// json = JSON.parse(j)
// populateFruits()
// }
function addOption(select, value, text) {
var option = document.createElement('option')
option.setAttribute('value', value)
option.textContent = text
select.appendChild(option)
}
function clearOptions(select) {
var children = select.children
var childrenToRemove = ;
for (var i = 1; i < children.length; i++) {
childrenToRemove.push(children[i])
}
for (var i = 0; i < childrenToRemove.length; i++) {
select.removeChild(childrenToRemove[i])
}
}
}())
<form>
<select name="fruits" size="4">
<option value="0">Select Fruit</option>
</select>
<select name="amount" size="4">
<option value="0" >Select Amount</option>
</select>
</form>
edited Nov 21 '18 at 14:00
answered Nov 21 '18 at 12:57
yunzenyunzen
20.8k84979
20.8k84979
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53410084%2ffilling-a-dropdown-list-based-on-another-dropdown-list-in-the-same-html-form%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
You don't need AJAX for this, but yes, you need JavaScript to detect a change on your first dropdown to fill the second dropdown.
– bart
Nov 21 '18 at 10:34
There are several way you can achieve this using only Js, one way, you can create all the possible price lists, make them all undisplayed, and only shows one of them according to fruit selection. Another way maybe, is to keep the price list empty, and just fill it with values only upon user’s fruit selection. Try those options and post back if you struggle with coding them.
– Ahmed Hammad
Nov 21 '18 at 10:35
But first, you'll have to defined your pricing for each option, in a JavaScript object or array.
– bart
Nov 21 '18 at 10:36
First question: Where do you get the prices from?
– yunzen
Nov 21 '18 at 10:40
@HerrSerker I just started coding so I am completly unaware of how to do this. I'm assuming your question is to know if I have a DB or not. No I don't right now but I could make it based on your answers to the question. Since I'd like to learn, let's say I have a database with those values inside:
id_fruit fruit_name price_1kg price_2kg price_3kg
– TheNoobUser
Nov 21 '18 at 10:45