views:

139

answers:

2

I want to select a particular RadioButton based on its value

<input id="RadioJ" type="radio" name="grp1" value="AAA" />
<input id="FaroK"  type="radio" name="grp1" value="BBB" />
<input id="MartreLK" type="radio" name="grp1" value="CCC" />

Something like this:

var radio = radio button whose value is BBB

Another thing i am looking is that if a button is clicked, all the radiobuttons which are hidden should be visible.

+5  A: 

You can select based on the value directly, e.g.:

var radio = $("input[type='radio'][value='BBB']")
Andrew Barrett
what's difference between input[type='radio'] and input:radio..which is better?
KJai
@KJai: input[type='radio'] and input:radio will both work. The [attr=value] selector will work for any attribute, the second is a pseudo selector that will internally do the same I guess.
Tim Büthe
A: 

Assuming you have a <form> element surrounding your radio buttons:

function getRadioWithValue(form, groupName, val) {
  var radios = form.elements[groupName];
  var i = radios.length, radio;
  while (i--) {
    radio = radios[i];
    if (radio.value === val) {
      return radio;
    }
  }
  return null;
}

var radio = getRadioWithValue(document.forms["your_form_name"], "grp1", "BBB");

This will be an awful lot more efficient and fast than the jQuery equivalent using unnecessary CSS selectors.

Tim Down
I'd be interested to know if it made any perceptible difference on a page with a moderately complex DOM. I might do some benchmarking tonight for fun.
Andrew Barrett
I'd be interested to see the results.
Tim Down
(Saving nanoseconds on client machine) OR (Saving 10 lines of bandwidth)Choice is yours.
Krishna Kant Sharma
And what if radio is not inside a form.
Krishna Kant Sharma
@KrishnaYour first point about saving bandwidth is valid if jQuery is already being used for something worthwhile elsewhere on the page. Otherwise, the argument about bandwidth becomes 10 lines (around 330 bytes) versus 50K.Regarding the question about if the radio buttons are not in a form: yes, my approach won't work. It wouldn't be hard to adapt my code to use getElementsByName and check for name and value.
Tim Down
In this case the question is tagged jquery, so I think it's safe to assume jquery will be present.
Andrew Barrett