David Edwards David Edwards - 4 months ago 13
jQuery Question

How to know if the 7th radio button is selected without knowing name or id

I have a product page that dynamically creates item options. I would like to know if the 7th option is selected, but I wont know the "name" or "id" of the radio button because they are generated automatically.



function teasamplecheck() {
if(document.form1.radio1[7].checked == true) {
alert("You have selected a sample");
}
else {
// DO NOTHING
}
}
}
});





<!--START: radio-format-->
<div class="radio-format" itemprop="offers" itemscope itemtype="http://schema.org/Offer">
<input type="radio" name="[oname]" id="radio-[value]" value="[value]" onClick="teasamplecheck();validateValues(document.add,1);updateprice();" [selected]>
[feature]
<div class="clear"></div>
</div>
<!--END: radio-format-->


So how to I look at this set of radio buttons and know that the 7th one is selected?

Answer

The use of the jQuery .eq() may be a way.

function teasamplecheck() {
    if( $(".radio-format input").eq(6).prop("checked") ) {
        alert("You have selected a sample");
    }
    else {
        // DO NOTHING
    }
}

This is .eq(6) because the argument is zero-based.

So... This is the 7th input inside its parent radio-format...
If you have the whole radio-format div repeated many times... It would be :

function teasamplecheck() {
    if( $(".radio-format").eq(6).children("input").prop("checked") ) {
        alert("You have selected a sample");
    }
    else {
        // DO NOTHING
    }
}

EDIT
See question in comments

To trigger the alert ONLY if the click has occured on the 7th radio, you to change the condition:

function teasamplecheck(obj) {
    if (( obj.value == $(".radio-format input").eq(6).val() ) && ( obj.checked )){
        alert("You have selected a sample");
    }
    else {
        // DO NOTHING
    }
}

OR (if the whole radio-format div is repeated) :

function teasamplecheck(obj) {
    if (( obj.value == $(".radio-format").eq(6).children("input").val() ) && ( obj.checked )){
        alert("You have selected a sample");
    }
    else {
        // DO NOTHING
    }
}

It compares the value of the obj passed by the onclick handler:

onClick="teasamplecheck(this); ...