skip to Main Content

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


  1. 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 be var 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:

    // 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);
    }
    
    // Event listener for dropdown change
    select_city.addEventListener('change', function() {
        var chosen_city = this.value; // Get the currently selected city
    
        if (chosen_city == "Location 1") {
            document.getElementById("output").innerHTML = "10 USD";
        } else if (chosen_city == "Location 2") {
            document.getElementById("output").innerHTML = "20 USD";
        } else if (chosen_city == "Location 3") {
            document.getElementById("output").innerHTML = "30 USD";
        } else {
            document.getElementById("output").innerHTML = ""; // Clear the output if no city is selected
        }
    });
    

    This code will dynamically update the shipping cost whenever a different city is selected from the dropdown.

    Login or Signup to reply.
    1. Create an array of objects to model HTML <option /> element (i.e. text, value)
    2. Iterate the array and create a new <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
    3. Add an event listener to the dropdown so that on change, the output element is updated with the .value of the corresponding location.

    JavaScript Example

    const locations = [
      { text: "-- Choose City --", value: "" },
      { text: "Location 1", value: "10 USD" },
      { text: "Location 2", value: "20 USD" },
      { text: "Location 3", value: "30 USD" },
    ];
    
    const dropdown = document.getElementById("city");
    
    locations
      .forEach((location, id) => dropdown[id] = new Option(location.text, id.toString()));
    
    dropdown.addEventListener("change", (evt) => {
      const output = document.getElementById("output");
      output.innerHTML = locations[evt.target.value].value;
    });
    

    TypeScript Example

    type Options = Array<{
      text: string;
      value: string;
    }>;
    
    const locations: Options = [
      { text: "-- Choose City --", value: "" },
      { text: "Location 1", value: "10 USD" },
      { text: "Location 2", value: "20 USD" },
      { text: "Location 3", value: "30 USD" },
    ];
    
    const dropdown = document.getElementById("city");
    
    locations
      .forEach((location, id) => dropdown[id] = new Option(location.text, id.toString()));
    
    dropdown.addEventListener("change", (evt) => {
      document.getElementById("output").innerHTML = locations[evt.currentTarget.value].value;
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search