开发者

How get object from each function

I have a <div> with rabioboxs:

<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&开发者_运维问答gt;<input type='radio' name='RB01' value='3'><br />
</div>

Then with jquery I want to get a radiobox that was checked:

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

but in the end obj = null.


You should do:

if ($(this).is(':checked') == true)

or

 if (this.checked == true)

Of course rember to have at least on of the checkbox checked. Fiddle here http://jsfiddle.net/nicolapeluchetti/Ky6q2/ and here http://jsfiddle.net/nicolapeluchetti/TEw53/


var radio = $('#RB-01 input:radio:checked');
console.log(radio);


you can use the :checked selector like this:

var selectedRadios = $('#RB-01 input:checked');


The jQuery object doesn't have any checked property. Just don't create a jQuery object from the element.

Notes: You can use the # operator in the selector instead of [id=...]. You don't need to check if a selector returns anything before looping, it's perfectly valid to loop an empty jQuery object. You don't have to compare a boolean value to true to check if it's true.

var obj = null;
var tempId = "RB-01";
$('div#' + tempId + ' input').each(function() {
  if (this.checked) obj = $(this);
});

You could even use a selector to find the checked element:

var tempId = "RB-01";
var ch = $('div#' + tempId + ' input:checked');
var obj = ch.length > 0 ? ch.last() : null;

(Note: I used the last method to get the last matched element so that it works the same as the code with the loop. If you know that there is only one checked element, you can just as well use the first method instead.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜