简体   繁体   中英

How to get value of a selected radio button?

I have a <div> with radioboxes:

<div id='RB-01'>
<span>Item_1</span><input type='radio' name='RB01' value='1'><br />
<span>Item_2</span><input type='radio' name='RB01' value='2'><br />
<span>Item_3</span><input type='radio' name='RB01' value='3'><br />
</div>

Then with jQuery I want to get number on an account a radiobox that was checked:

var obj;
var tempId = "RB-01";
if ($('div[id=' + tempId + ']')) {
  $('div[id=' + tempId + '] input').each(function() {

  ...here I need save in the variable obj the number on an account input that was checked... 

  }); 
}   
var obj = null;
var tempId = "RB-01";

if ($('div[id=' + tempId + ']')) {
  obj = $('#' + tempId + ' input:checked').val();
}

There's no need to use the div[id=RB-01] selector since IDs are unique. Just use #RB-01 . Then use the :checked selector to get the checked radio button.

var obj = null,
    tempId = "RB-01",
    $div = $('#'+tempId);

if ($div.length){
    obj = $div.find('input:radio:checked').val();
}

Here is a demo

Sounds like you need

  $('div[id=' + tempId + '] input:checked').each(function() {

  var number = $(this).val();

  }); 

You could have quite easily found this on the jQuery API site...

JQuery each !

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