Search code examples
javascriptjqueryhtmlradio-buttonjradiobutton

Determine which radiobutton is checked with javascript


Hi everyone can someone please help me with the following problem.

// i have written the problem inside the javascript

See http://jsfiddle.net/7Cmwc/3/ for example.

 function calculate() 
//If radiobutton with ID box3 is checked do this mybox1*mybox2+5
{
        var myBox1 = document.getElementById('box1').value; 
        var myBox2 = document.getElementById('box2').value;
        var result = document.getElementById('result'); 
        var myResult = myBox1 * myBox2 + 5 ;
        result.value = myResult;
      }

//If radiobutton with ID box4 is checked do this mybox1*mybox2+10
{
        var myBox1 = document.getElementById('box1').value; 
        var myBox2 = document.getElementById('box2').value;
        var result = document.getElementById('result'); 
        var myResult = myBox1 * myBox2 + 10 ;
        result.value = myResult;
      }

//If radiobutton with ID box3 is checked do this mybox1*mybox2+15
{
        var myBox1 = document.getElementById('box1').value; 
        var myBox2 = document.getElementById('box2').value;
        var result = document.getElementById('result'); 
        var myResult = myBox1 * myBox2 + 15 ;
        result.value = myResult;
      }

And also i wonder what the difference is between jradiobutton and radiobutton?

Thanks in advance


Solution

  • Not saying I would do it this say, but this is a simple example to show you how it's done, at the very basic level.

    function calculate()  {
    
        var myBox1 = document.getElementById('box1').value,
            myBox2 = document.getElementById('box2').value,
            myBox3 = document.getElementById('box3').checked,
            myBox4 = document.getElementById('box4').checked,
            myBox5 = document.getElementById('box5').checked,
            result = document.getElementById('result'),
            myResult;
    
        if ( myBox3 ) {
          myResult = myBox1 * myBox2 + 5 ;
          result.value = myResult;
        }
    
        else if ( myBox4 ) {    
           myResult = myBox1 * myBox2 + 10 ;
           result.value = myResult;
        }
    
        else if ( myBox5 ) {
           myResult = myBox1 * myBox2 + 15 ;
           result.value = myResult;
        }
    }