Walid
Walid

Reputation: 1282

Selector to get the checked radio within a list of radio I already got

Summary of what I am trying to do: I have got a list of radio boxes (I got it using a jquery selector) and I would like to get the one that is checked within that list without evaluating the first selector again. Example:

var radioBoxes = $(this).parent().find(":radio");
if (radioBoxes.length > 0)
{
    var radioBoxValue = $(this).parent().find(":radio:checked");
    //Do something with checked radio value
}
else
{
    //I found no radio so to something else
}

So is there any selector that I could run on radioBoxes to get the checked radio?

If you want more details, here they are. I have implemented a control that contains some checkboxes that have a list of radio buttons near to them:

    [x] Java   ( )1  (x)2  ( )3
    [x] Ajax   ( )1  ( )2  ( )3

But in the same control, I also have checkboxes that have no radio near to them:

    [x] Developper / Programmer
    [ ] Technical Analyst

I would like to avoid doing the following:

$(':checkbox').click(function(){
    if ($(this).parent().find(":radio").length > 0)
    {
        //I am a checkbox who has radios near to me,
        //I want to known which radio is checked if any
        var value = $(this).parent().find(":radio:checked").val();
        //...
    }
    else
    {
        //I am a checkbox who has no radio near to me
        //...
    }             
});

Because I do not like evaluating both

$(this).parent().find(":radio")

and

$(this).parent().find(":radio:checked")

I would like something like:

$(':checkbox').click(function(){
    var radioBoxes = $(this).parent().find(":radio");
    if (radioBoxes.length > 0) 
    {
        var value = radioBoxes.has(":checked");
        //...
    }
    else
    {
        //...
    }
});

But that does not work.

Does anyone know if such a feature exists in jquery?

Upvotes: 0

Views: 153

Answers (2)

Walid
Walid

Reputation: 1282

Problem solved: as suggested by rjz, it just needs filter() function:

$(':checkbox').click(function(){
    var radioBoxes = $(this).parent().find(":radio");
    if (radioBoxes.length > 0) 
    {
        var value = radioBoxes.filter(":checked").val();
        //...
    }
    else
    {
        //...
    }
});

Upvotes: 0

rjz
rjz

Reputation: 16520

You could use .filter(":checked") on the existing collection of elements:

var radios = $(this).parent().find(":radio");

if (radios.length > 0)
{

    var value = radios.filter(":checked").val();
    //...
}

The skivvy on the filter method is available at: http://api.jquery.com/filter/

Upvotes: 2

Related Questions