Search code examples
htmlcsstextboxdropdowntextfield

Basic Dropdown Menu


im trying to add a basic dropdown menu that gives 5 possible selections. When you select this on the dropdown, there will be another field to the right that give that answer for that selection i.e:

Selecting France (on the dropdown), the field box on the right gives answer: Paris.

I'm using HTML, CSS - Sorry i'm not too good with coding and wondered if someone can help. Thanks.


Solution

  • See this. You need to use javascript to change text of the second field. I only made three choices, bout you should have not much trouble adding the two remaining.

    Be aware that countryInput.value gives the "name" of an option, not the displayed text. If you need explanation how the javascript works, there are better sites for that than stackoverflow.

    function cityChange() {
      var countryInput = document.getElementById("country");
      var cityInput = document.getElementById("city");
      var city = "";
      
      switch (countryInput.value) {
        case "france":
          city = "Paris";
          break;
        case "slovakia":
          city = "Bratislava";
          break;
        case "germany":
          city = "Berlin";
          break;
      }
      
      cityInput.value = city;
      
    }
    <select id="country" onchange="cityChange()">
      <option disabled selected> -- select a country -- </option>
      <option value="france">France</option>
      <option value="slovakia">Slovakia</option>
      <option value="germany">Germany</option>
    </select>
    <input type="text" id="city" readonly/>