I’m new to JavaScript and learning. I’m trying to create a dropdown of locations, and when selected, the shipping costs will dynamically shown for each location.
enter image description here
Here are my codes.
HTML:
<select name="city" id="city">
<option value="-">Choose city</option>
</select>
<p>Your estimated shipping cost: </p>
<p id="output"></p>
JavaScript:
// Add location array to city dropdown
var select_city = document.getElementById("city");
var city = ["Location 1";"Location 2";"Location 3"];
for(var i = 0; i < city.length; i++) {
let opt = city[i];
let el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select_city.appendChild(el);
};
// I'm stuck here at the moment, I don't know how to output dynamically base on selected
var chosen_city = select_city.options[select_city.selectedIndex].value;
if (chosen_city == "Location 1") {
document.getElementById("output").innerHTML = "10 USD";
} else if (chosen_city == "Location 2") {
document.getElementById("output").innerHTML = "20 USD";
} else {
document.getElementById("output").innerHTML = "30 USD";
};
Hope someone could help, because I don’t really know how to search for this problem here with the right keywords! Thanks in advance! 🙂
I tried using if and using function(), but it’s not dynamically changed.
2
Answers
I see a few issues and areas for improvement in your JavaScript code. Let’s go through them:
1. Array Declaration: In JavaScript, array elements are separated by commas, not semicolons. So, the line
var city = ["Location 1";"Location 2";"Location 3"];
should bevar city = ["Location 1", "Location 2", "Location 3"];
.2. Event Listener for Dropdown: You need to add an event listener to your dropdown to detect when the selected option changes. This is not present in your current code.
3. Dynamic Output: The logic for determining the shipping cost based on the selected city should be inside the event listener, so it gets triggered every time a new option is selected.
Here’s how you can modify your JavaScript code:
This code will dynamically update the shipping cost whenever a different city is selected from the dropdown.
<option />
element (i.e.text
,value
)<option />
element for each location adding it to the dropdown. Use the location text as the display text and it’s position in the array as the id.value
of the corresponding location.JavaScript Example
TypeScript Example