blyter
blyter

Reputation: 121

How to get value of option of a select element and use it in a calculation?

I'm doing an example for this javascript textbook and it's a simple calculator. There are two input (number) tags where the user selects a number and a select tag with options for a modifier (see code).

<input type="number" value="2" id='num1'>
<select id="operation">
    <option>+</option>
    <option>-</option>
    <option>*</option>
    <option>/</option>
    <option>%</option>
</select>
<input type="number" value="2" id='num2'> =
<input type='text' readonly>
<br>
<input id="button1" type="button" value="Do It!">

What I have to do is get the values of both the numbers and then calculate the operation based on which modifier is selected in the options.

window.addEventListener("load", function() {
    document.getElementById("button1").onclick = function(event) {
        var num1 = document.getElementById("num1").value;
        var num2 = document.getElementById("num2").value;
        var mod = document.getElementById("operation").selectedIndex;
    }
});

However, I don't understand how to do the calculation with the modifier. Would I need an if statement where it checks what value the mod has and then depending on that it does a certain calculation? Or is there a simpler way to just get the modifier and do a certain calculation that way?

Upvotes: 2

Views: 3630

Answers (2)

Scott Marcus
Scott Marcus

Reputation: 65845

You will need to perform some if/then testing to see which value was selected and the proceed from there.

Also, don't use inline HTML event handling attributes (onclick, onchange) as they:

  • create spaghetti code that is hard to read
  • create anonymous global wrapper functions that modify the this binding
  • don't follow W3C DOM Event Standards

Instead, follow standards and set up event handlers using .addEventListener()

Lastly, it's not a great UI design to use a textbox (even a readonly one) for output that will not be interacted with directly. Instead, use a non-form HTML element (like a <span>) to house the result. You can always style the element to look anyway you want.

// When the DOM is loaded
window.addEventListener("DOMContentLoaded", function(){

  // Get references to DOM elements, not their values
  // This allows you to refrence the element over and over
  // without having to re-scan the DOM for it
  var select = document.getElementById("operation");
  var oper1 = document.getElementById("num1");
  var oper2 = document.getElementById("num2");
  var result = document.getElementById("result");
  var btn = document.getElementById("button1");

  // Set up a click event handler for the button and the select:
  btn.addEventListener("click", count);
  select.addEventListener("change", count);

  function count() {
    var answer = null;
  
    // Convert the text values to numeric values
    var n1 = parseFloat(oper1.value);
    var n2 = parseFloat(oper2.value);

    // Determine the math operation needed and proceed accordingly
    switch (select.value){
      case "+":
        answer = n1 + n2;
        break;
      case "-":
        answer = n1 - n2;
        break;
      case "*":
        answer = n1 * n2;
        break;
      case "/":
        answer = n1 / n2;
        break;
      case "%":
        answer = n1 % n2;
        break;       
    }

    // Inject the answer into the HTML element
    result.textContent = answer; 
  }
});
<input type="number" value="2" id='num1'>
<select id="operation">
                <option>+</option>
                <option>-</option>
                <option>*</option>
                <option>/</option>
                <option>%</option>
            </select>
<input type="number" value="2" id='num2'> =
<span id='result'></span><br>
<input id="button1" type="button" value="Do It!">

Upvotes: 1

kind user
kind user

Reputation: 41893

You can do something like this. The function will be called even if you just change the mathematical operator in the select box.

If you want to get the selected value from the select box, you have to use the .value prop, same as a normal input.

function count() {
  var num1 = document.getElementById("num1").value;
  var num2 = document.getElementById("num2").value;
  var mod = document.getElementById("operation").value;
  document.getElementById('result').value = eval(num1 + mod + num2);
}
<input type="number" value="2" id='num1'>
<select id="operation" onchange='count()'>
                <option>+</option>
                <option>-</option>
                <option>*</option>
                <option>/</option>
                <option>%</option>
            </select>
<input type="number" value="2" id='num2'> =
<input type='text' readonly id='result'><br>
<input id="button1" type="button" value="Do It!" onclick='count()'>

Like Scott Marcus pointed, the eval() function is not really suggested to use anywhere in your project and I'm aware of that, but this is only for learning purposes.

Upvotes: 5

Related Questions