Search code examples
javascriptdropdowncalculated-field

JavaScript : How to get selected dropdown value?


I'm using code from w3schools & attempting to modify it so that the script will multiply by a different valNum based on the value selected from the drop down list. So if All Purpose Flour is selected the Output = Input multiplied by 4.409245; for Cane Sugar it would be Output = Input multiplied by 8.82.

Here's what I have so far. I plan to add more option values to the list but need help figuring out how to do this. I'm new to JavaSript; sorry if this looks odd. Any feedback is appreciated. Thanks!

<select name="ingredients" id="ingredients">
          <option value="flour">All Purpose Flour</option>
          <option value="sugar">Cane Sugar</option>
</select>
    
    
<p>
  <label>Pounds</label>
   <input id="inputPounds" type="number" placeholder="Pounds" oninput="weightConverter(this.value)" onchange="weightConverter(this.value)">
</p>
<p>Ounces: <span id="outputOunces"></span></p>
    
    
 <script>
    function weightConverter(valNum) {
      document.getElementById("outputOunces").innerHTML=valNum*4.409245;
    }
 </script>


Solution

  • Updated your code with a few pointers -

    • To add another option, say Cheese with multiplier of 2, you can just add the option in the HTML under the select element and add a new case in the switch statement as shown in the below code.
    • Have added the method weightConverter for the onChange of the select component for the case when user enters some value first in the input box and then decides to change their mind and change the value in the select component, it re-evaluates the Output after changing the option in the select component.

    <select name="ingredients" id="ingredients" onChange="weightConverter()">
      <option value="flour">All Purpose Flour</option>
      <option value="sugar">Cane Sugar</option>
      <option value="cheese">Cheese</option>
    </select>
    <p>
      <label>Pounds:</label>
      <input id="inputPounds" type="number" placeholder="Pounds" oninput="weightConverter()">
    </p>
    <p>Ounces: <span id="outputOunces"></span></p>
    
    
    <script>
      function weightConverter() {
        const dropDownValue = document.getElementById('ingredients').value;
        const valNum = document.getElementById('inputPounds').value;
        let multiplier = 0;
        switch (dropDownValue) {
          case 'flour':
            multiplier = 4.409245;
            break;
          case 'sugar':
            multiplier = 8.82;
            break;
          case 'cheese':
            multiplier = 2;
            break;
          default:
            break;
        }
        document.getElementById("outputOunces").innerHTML = valNum * multiplier;
      }
    </script>