How can I read the value of a radio button in JavaScript?

Posted by Corey on Stack Overflow See other posts from Stack Overflow or by Corey
Published on 2010-03-13T17:31:43Z Indexed on 2010/03/13 18:55 UTC
Read the original article Hit count: 240

Filed under:
|
<html>

<head>
<title>Tip Calculator</title>

<script type="text/javascript"><!--
function calculateBill(){
  var check = document.getElementById("check").value;

  /* I try to get the value selected */
  var tipPercent = document.getElementById("tipPercent").value;

  /* But it always returns the value 15 */   
  var tip = check * (tipPercent / 100)
  var bill = 1 * check + tip;
  document.getElementById('bill').innerHTML = bill;
}
--></script>
</head>

<body>

<h1 style="text-align:center">Tip Calculator</h1>

<form id="f1" name="f1">
Average Service:   15%
<input type="radio" id="tipPercent" name="tipPercent" value="15" />
<br />

Excellent Service: 20%
<input type="radio" id="tipPercent" name="tipPercent" value="20" />
<br /><br />

<label>Check Amount</label>
<input type="text" id="check" size="10" />
<input type="button" onclick="calculateBill()" value="Calculate" />
</form>

<br />
Total Bill: <p id="bill"></p>

</body>
</html>

I try to get the value selected with document.getElementById("tipPercent").value, but it always returns the value 15.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about html