views:

58

answers:

2

So, I have radio boxes of the form

<li><input type="radio" name="names" value="blah"><a>Some text (blah)</a></li>

There are 100 plus of these radio buttons.

Now, I have a jQuery filter, from here. The filter works well.

But, I want to set a jQuery statement that will auto select the radio button if it is, amongst the shown, the only one remaining.

The filter uses show() and hide(), which I presume means it switches it from display: block to display: none;

My best crack at doing this on my own looks like this, but it's not working:

     if($('li').attr({"display":"block"}).size()==1)
      {
      $('input[cvs_name]:eq(1)').attr('checked', 'checked');
      }

How can I do this?

+4  A: 
var $visible = $('ul').find('li:visible');
if($visible.length == 1) {
    $visible.find('input:radio').attr('checked','checked');
}
Paolo Bergantino
This works, except, for some reason, instead of 1, it's setting length to 10 when there is 1, 11 when there are 2, etc. It's easy enough to work around it by setting the condition to ==10, but any idea why that could be happening?
yc
Ah, its because there are 9 other <li> buttons. Changed 'ul' to be ul#list (the id of the ul in question), and it worked.
yc
+1  A: 

Try this:

if ($("li:visible").length === 1) {
    $("li:visible input").attr("checked", "checked");
}

jQuery has a visible filter which only selects elements which aren't hidden. (And, of course, a hidden filter which selects those which are.)

Ben Blank