简体   繁体   中英

Javascript getting information from radio buttons

So I have this:

<input type="radio" value="<10"> Less than 10 Bubbles
<br />
<input type="radio" value="10"> 10 Bubbles
<br />
<input type="radio" value="10"> More than 10 Bubbles

<br /><br />
<input type="button" onclick="CalculatePrice()" value="Calculate Price">

And basically I want to be able to do some code depending on what radio button is selected, how would I do this?

Thanks!

      <script>
 function CalculatePrice()
{

If($(#radiobtn1).is(':checked'))
{
  var a=2+1;
  alert(a);
}
 If($(#radiobtn2).is(':checked'))
{
  //some code
}


 }


      </script>

Give a name for each input:

<input type="radio" name="bubble" value="5"> Less than 10 Bubbles
<br />
<input type="radio" name="bubble" value="10"> 10 Bubbles
<br />
<input type="radio" name="bubble" value="30"> More than 10 Bubbles
<br />
<button onclick="getValues();">Get values</button>

Javascript to access the value of selected button:

function getValue(n) {
 var i, r = document.getElementsByName(n);
 for (i = 0; i < r.length; i++) {
   if (r[i].checked) return r[i].value;
 }
 return '';
}

function getValues() {
 var g = getValue('bubble');
 alert(g);
}

You can use jQuery. just give the radio buttons a class attribute, and you're good to go with this basic script:

$('.radio-button-class-name').each(function(){
   $(this).click(function(){
      // Do stuff here
   });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM