kronis72
kronis72

Reputation: 311

radio button .checked to perform a math expression using user input javascript

I have two textboxes where a user enters a number into each one and then clicks a radio button to select the mathematical operation to be performed upon the calculate button.This is for a homework assignment, so only javascript and html are being used, no jquery. Currently when I click the button, nothing appears to happen and I am getting no console errors...

HTML

<div>
    <p>Enter two numbers, select a math, then click the button.<br>
    The answer will be shown below.</p>
    <form>
        1st number: <input type="text" name="number1">
        2nd number: <input type="text" name="number2">
        <br>
        <input type="radio" name="add">Add <br>
        <input type="radio" name="subtract">Subtract <br>
        <input type="radio" name="multiply">Multiply <br>
        <input type="radio" name="division">Division <br>
        <input type="button" name="calc" onclick="calculate()" value="Calculate"> <br>              
    </form>
    <p id="math_res"></p>
</div>

Javascript

function calculate(){
    var num1 = parseInt("document.getElementsByName('number1').value;", 10);
    var num2 = parseInt("document.getElementsByName('number2').value;", 10);
    var add = document.getElementsByName("add");
    var sub = document.getElementsByName("subtract");
    var multi = document.getElementsByName("multiply");
    var divis = document.getElementsByName("division");
    var res = document.getElementById("math_res").innerHTML;

    if (add.checked == true){
        res = num1 + num2;
    }
    else if ( sub.checked == true){
        res = num1 + num2;
    }
    else if (multi.checked == true){
        res = num1 * num2;
    }
    else if (divis.checked == true){
        res = num1 / num2;
    }
}

I thought my function would take the input from the two text boxes and convert the user input to an integer and assign them to variable num1 and num2. Then assign each radio button to a variable to reduce typing of document.get... that each if statement would check to see if that radio but was checked. If true perform calculation if false move to next if statement and display the results in a paragraph element.

where did I go wrong?

Upvotes: 0

Views: 5562

Answers (3)

FlokiTheFisherman
FlokiTheFisherman

Reputation: 234

Here is my version, hope it helps you.

<!DOCTYPE html>
<html>
<body>
    <div>
        <p>Enter two numbers, select a math, then click the button.<br>
        The answer will be shown below.</p>
        <form>
            1st number: <input type="text" name="number1" id = 'number1'>
            2nd number: <input type="text" name="number2" id = 'number2'>
            <br>
            <input type="radio" name="button" id = 'add' >Add <br>
            <input type="radio" name="button" id = 'substract'>Subtract <br>
            <input type="radio" name="button" id = 'multiply'>Multiply <br>
            <input type="radio" name="button" id = 'division'>Division <br>
            <input type="button" name="calc" onclick="calculate()" value="Calculate"> <br>              
        </form>
        <p id="math_res"></p>
    </div>

    <script>
        function calculate(){
            //Obtaining the references to the text inputs
            var number1 = parseInt(document.getElementById('number1').value);
            var number2 = parseInt(document.getElementById('number2').value);

            //Reference of the result Box
            var resultBox = document.getElementById('math_res');
            resultBox.innerHTML = '';

            //Reference of the radio buttons
            var buttonAdd = document.getElementById('add');
            var buttonSubstract = document.getElementById('substract');
            var buttonMultiply = document.getElementById('multiply');
            var buttonDivision = document.getElementById('division');

            //Make the magic
            if(buttonAdd.checked == true){
                resultBox.innerHTML = number1 + number2
            }
            else{
                if(buttonSubstract.checked == true){
                    resultBox.innerHTML = number1 - number2
                }
                else{
                    if(buttonMultiply.checked == true){
                        resultBox.innerHTML = number1 * number2
                    }
                    else{
                        if(buttonDivision.checked == true){
                            resultBox.innerHTML = number1 / number2
                        }
                    }
                }
            }            
        }

    </script>
</body>

Upvotes: 0

Igor Raush
Igor Raush

Reputation: 15240

There are a few issues I can notice.

1. getElementsByName returns a NodeList, which is Array-like. You need to retrieve the first element in the NodeList before accessing its value. For example,

document.getElementsByName('number1')[0].value

2. You are passing a literal code string to parseInt. You should write something like

parseInt(document.getElementsByName('number1')[0].value, 10);

3. The code var res = document.getElementById('math_res').innerHTML stores a reference to the innerHTML of the element. When you assign res = num1 + num2 for example, you are simply overwriting the reference, instead of actually altering the innerHTML. To correct this,

var elem = document.getElementById('math_res');

// later...
elem.innerHTML = num1 + num2;

4. You are incorrectly defining multiple radio buttons with different names. In order for the browser to render them as a "radio button group" where only one can be selected, they must have the same name, but different "value" attributes. See RobG's answer or the Plunkr below for an example of how to define the radio button group and extract its value using JavaScript.

A working version of your code is here.


Edit Please note that these are minimal edits to make your code work. RobG's answer shows a more correct way of extracting the values of form fields.

Upvotes: 2

RobG
RobG

Reputation: 147403

You have a couple of issues.

getElementsByName returns a collection of elements, not a single element so:

 var add = document.getElementsByName("add");

will assign undefined to add. But you don't need to use it, just reference the controls as named properties of the form. Pass a reference to the button from the listener:

<input type="button" name="calc" onclick="calculate(this)" value="Calculate">

Then in the function get the form:

function calculate(element) {
  var form = element.form;

Now just do:

var num1 = parseInt(form.number1.value, 10);

and so on, which also fixes the other issues you have with referencing the controls.

Also, radio buttons need to have the same name so that only one is selectable, so as Felix says, give them all the same name and differentiate on value (or class or some other attribute value). You'll need to loop over them to find out the operation to perform, so the HTML might be:

  <input type="radio" name="operation" value="add">Add <br>
  <input type="radio" name="operation" value="subtract">Subtract <br>
  <input type="radio" name="operation" value="multiply">Multiply <br>
  <input type="radio" name="operation" value="division">Division <br>

Then to get the operation:

  var radios = form.operation;
  var op;
  for (var i=0; i<radios.length; i++) {
    if (radios[i].checked) {       
       op = radios[i].value;
       break;
    }
  }

Now check the value of op to work out whether to add, subtract, etc.

Here's a quick example, I don't recommend inline scripts like this but it's handy for playing.

<form>
  <input type="radio" name="operation" value="add">Add <br>
  <input type="radio" name="operation" value="subtract">Subtract <br>
  <input type="radio" name="operation" value="multiply">Multiply <br>
  <input type="radio" name="operation" value="division">Division <br>
  <input type="button" onclick="
    var form = this.form;
    var radios = form.operation;
    var op;
    for (var i=0; i<radios.length; i++) {
      if (radios[i].checked) {       
         op = radios[i].value;
         break;
      }
    }
    form.selectedOperation.value = op || 'No operation selected';
  " value="Get selected operation">
  <input type="text" readonly name="selectedOperation"><br>
  <input type="reset">
</form>

Upvotes: 2

Related Questions