Using if else statement with radio buttons in javascript
20,416
Looks like your javascript is missing a }
<html>
<head>
<title>Calculator</title>
<script language="javascript" type="text/javascript">
function packageTotal() {
// Enter in prices here
var x = 5;
var y = 10;
var p = x + y * 12;
var b = y * 12;
if (document.getElementById('basicProgram').checked) {
// Basic package is checked
document.calculator.total.value = b;
} else if (document.getElementById('proProgram').checked) {
// Pro package is checked
document.calculator.total.value = p;
}
}
</script>
</head>
<body>
<!-- Opening a HTML Form. -->
<form name="calculator">
<!-- User fills out form here -->
<br />
<input type="radio" name="programType" id="basicProgram" value="Basic" /> Basic
<input type="radio" name="programType" id="proProgram" value="Pro" checked /> Pro
<!-- Here result will be displayed. -->
<br />
Your total price is: <input type="text" name="total">
<input type="button" value="Submit" onclick="javascript:packageTotal();">
</form>
</body>
</html>
Demo: Fiddle
Author by
SS SS
Updated on July 28, 2022Comments
-
SS SS almost 2 years
I am trying to use an if else statement to do a certain action if one radio button is selected and do a different action if another is selected. In this case I want to use one formula if the basic button is selected and the pro formula if the pro button is selected. I am new to programming so apologies in advanced.
<html> <head> <title>Calculator</title> <script language="javascript" type="text/javascript"> function packageTotal(){ //Enter in prices here var x = 5; var y = 10; var p = x + y*12; var b = y * 12; if(document.calculator.getElementById('basicProgram').checked) { //Basic package is checked document.calculator.total.value=b; }else if(document.calculator.getElementById('proProgram').checked) { //Pro package is checked document.calculator.total.value=p; } </head> <body> <!-- Opening a HTML Form. --> <form name="calculator"> <!-- User fills out form here --> <br /> <input type="radio" name="programType" id="basicProgram" value="Basic" /> Basic <input type="radio" name="programType" id="proProgram" value="Pro" checked /> Pro <!-- Here result will be displayed. --> <br /> Your total price is: <input type="text" name="total"> <input type="button" value="Submit" onclick="javascript:packageTotal();"> </form> </body> </html>
-
Mr_Green almost 11 yearsThere were some typos.. which I fixed. Here is the fiddle.
-
SS SS almost 11 yearsThank you very very much! Problem is resolved!
-
-
Mohammad Masoudian almost 11 yearswhy return false ? that is button
-
Arun P Johny almost 11 years@MohammadMasoudian missed that