tags:

views:

10129

answers:

2

I have the following markup, and I want to make the 'All' radio button checked.

<ul>
<li><input type="radio"  value="All"  name="Foo"  />All</li>
<li><input type="radio"  value="New"  name="Foo"  />New</li>
<li><input type="radio"  value="Removed"  name="Foo"  />Removed</li>
<li><input type="radio"  value="Updated"  name="Foo"  />Updated</li>
</ul>

I'd like to do it via attribute match, but I need to match on 2 attributes, @name='Foo' and also @value='All'

Something like this, (although it doesn't work):

$("input[@name='Foo' @value='all']).attr('checked','checked');

Can someone show how this can be done?

+11  A: 

The following HTML file shows how you can do this:

<html>
  <head>
    <script type="text/javascript" src="jquery-1.2.6.pack.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){
        $("a").click(function(event){
          $("input[name='Foo'][value='All']").attr('checked','checked');
          event.preventDefault();
        });
      });
    </script>
  </head>
  <body>
    <ul>
      <li><input type="radio"  value="All"  name="Foo"  />All</li>
      <li><input type="radio"  value="New"  name="Foo"  />New</li>
      <li><input type="radio"  value="Removed"  name="Foo"  />Removed</li>
      <li><input type="radio"  value="Updated"  name="Foo"  />Updated</li>
    </ul>
    <a href="" >Click here</a>
  </body>
</html>

When you click on the link, the desired radio button is selected. The important line is the one setting the checked attribute.

paxdiablo
Why the attributeEndsWith selector (name$) instead of just attributeEquals?To the OP - note that @ in front of attributes has been deprecated.
Mark Brackett
@MarkBrackett - it was lifted from some similar code of mine which had lots of similarly named unnumbered-list groups and I'd done the lot with one statement.I copied the code in but didn't edit that bit, so I'll change it now - thanks for the heads-up.
paxdiablo
+1  A: 

I was beating my head against a wall similar to this and just want to point out that in jQuery 1.3 the syntax used in the accepted answer is the ONLY syntax that will work. The questioner uses the @ syntax for the expression which does not work at all in jQuery. Hopefully this helps the next guy to come across this question via Google =p

To be clear, you have to use jQuery('input[name=field1][val=checked]') and not jQuery('input[@name=field1][@val=checked]')

easel