-1

I am trying to do arithmetic operation based on radio button value.

<html>
  <body>
    <br>Enter first number:
    <input type="text" id="txt1" name="text1">Enter second number:
    <input type="text" id="txt2" name="text2">
    
    <form>
      <input type="radio" name="oper" value="1" checked>Add
      <br>
      <input type="radio" name="oper" value="2">Multiply
      <br>
      <input type="radio" name="oper" value="3">Subtract
    </form> 




    <p id="demo"></p>
    <script>
      function myFunction() {
        var y = document.getElementById("txt1").value;
        var z = document.getElementById("txt2").value;
 var o = getCheckedRadioValue("oper");
 if(+o == 1)
         var x = +y + +z;
 
 if(+o == 2)
  var x = +y * +z;
  
 if(+o == 3)
  var x = +y - +z;
  
  
     
 
        document.getElementById("demo").innerHTML = x;
      
    </script>
    <button onclick="myFunction()">Calculate</button>
    <br/>
  </body>
</html>
Roope Hakulinen
  • 7,326
  • 4
  • 43
  • 66
Naresh
  • 334
  • 1
  • 4
  • 17
  • 1
    you are using a function `getCheckedRadioValue` which is not defined in your example. could you show the code for that function – olly_uk Apr 10 '15 at 07:39
  • possible duplicate of [Get Radio Button Value with Javascript](http://stackoverflow.com/questions/9618504/get-radio-button-value-with-javascript) – Interrobang Apr 10 '15 at 07:40

2 Answers2

0

You might be have problem with getCheckedRadioValue function.

To get the radio button check box values using jQuery

var o = $("input:radio[name='oper']:checked").val();

Try to Execute like this

 <script>
      function myFunction() {
        var y = document.getElementById("txt1").value;
        var z = document.getElementById("txt2").value;
    var o = $("input:radio[name='oper']:checked").val();
    if(+o == 1)
            var x = +y + +z;

    if(+o == 2)
        var x = +y * +z;

    if(+o == 3)
        var x = +y - +z;

      //  alert(x);

        document.getElementById("demo").innerHTML = x;
      }
    </script>

    <br/>
  </body>
</html>

Thanks.

Krishna38
  • 707
  • 1
  • 16
  • 43
  • If your just going to provide fixed code, you could at least explain what was wrong and what your code does to fix it – olly_uk Apr 10 '15 at 07:44
0

Try Like this :


Enter first number:
Enter second number:

<form>
    <input type="radio" name="oper" value= 1 checked />Add
<br>
    <input type="radio" name="oper" value=2 />Multiply
<br>
    <input type="radio" name="oper" value=3 />Subtract
</form> 
    <p id="demo"></p>
     <button id="submit">Calculate</button>


    $( "#submit" ).click(function() {
       var y = $("#txt1").val();
        var z = $("#txt2").val();
        var selected =  $("input[type='radio']:checked");
    var o =selected.val();

    if(o == 1)
            var x = +y + +z;

    if(o == 2)
        var x = +y * +z;

    if(o == 3)
        var x = +y - +z;
$("#demo").html(x);


    });