views:

28

answers:

2

Hi All

When using the each() function in jquery for a group of, let's say, 3 radio buttons, how do I retrieve the 3rd button so when it's checked something happens? Basically how do I choose the element I want to work with from the each() function?

Here is my coding:

HTML:

<form id="orderDefinition" name="orderDefinition">
  <fieldset>
    <input type="radio" name="radioGroup" /><label for="">radio 1</label>
    <input type="radio" name="radioGroup" /><label for="">radio 2</label>
    <input type="radio" name="radioGroup" /><label for="">radio 3</label>    
  </fieldset>
</form>

jQuery:

var radioBtnCollection = $("#orderDefinition input:radio");

$(radioBtnCollection).each(function(){
    // From here, I don't know how to get the element
});

Thanks in advance.

+2  A: 

You can refer to the element using the this operator:

radioBtnCollection.each(function(){
    alert(this.name);
});

Or by using the arguments supplied to the function:

radioBtnCollection.each(function(index, element){
    if (index == 2 && element.checked)
        alert("3rd element is checked!");
});

If you want to perform any jQuery methods on the element, you will need to wrap it with jQuery. For the first example, $(this), for the second example $(element).

You can just get the third radio button using :eq(2), instead of each:

if ($("#orderDefinition input:radio:eq(2)")[0].checked)
    alert("3rd element is checked!");
Andy E
@Andy E: thanks man. it works!! Another question (sorry), how do I make sure that a radio button has to be checked in jquery?
Shaoz
@Shoaz: you can use the `:checked` selector, for example, `$('input:radio:checked')` would get the currently checked radio element.
Andy E
@Andy E: No. Basically, I have this project where if you select the 3rd radio button, from the code above, it would highlight a group of checkboxes. But now the client also wants that when 1 of the checkboxes is checked, the the 3rd radio button is selected automatically as it they belong to the that radio button. I hope this was clear. I wanna know how to use jquery to achieve this. Sorry I'm kinda new to jquery...
Shaoz
A: 

Use this wrapped as a jQuery object:

$(radioBtnCollection).each(function(){
    // this points to the element being iterated
    $(this)
});
kgiannakakis