开发者

How to make a radio button selected using its value

In my code i am using a group of radio button having same id and name for all of the radio buttons.. but its value is different...

I have that value of the radio button that i want to be selected.. how can select that radio button using the value i have. consider an example..

 <input name="newColorCode" id="newColorCode" type="radio" value="color_code_LightViolet"/>
<input name="newColorCode" id="newColorCode" type="radio" value="color_code_red"/>
<input name="newColorCode" id="newColorCode" type="radio" value="color_code_green"/>

i have the value color_code_gre开发者_StackOverflow社区en.. how can i make the corresponding radio button selected using jquery????

i tried this

       $('input:radio[value=color_code_green]').checked=true;

but its not working


First, ids must be unique in the whole DOM. So having 3 radios with id="newColorCode" is wrong. So start by removing those id attributes or provide unique ones for each button. Then to answer your question:

$(':radio[value="color_code_green"]').attr('checked', 'checked');

And here's a live demo.

The reason your code doesn't work is because the $(..) function returns an array of jQuery wrapped DOM elements for which the checked property which you are trying to set is simply not defined. So you could use the .attr() function in order to do this to all elements returned by your selector.


You can do it in JavaScript also:

function getSelectedRadio(buttonGroup) {
   // returns the array number of the selected radio button or -1 if no button is selected
   if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            return i
         }
      }
   } else {
      if (buttonGroup.checked) { return 0; } // if the one button is checked, return zero
   }
   // if we get to this point, no radio button is selected
   return -1;
} // Ends the "getSelectedRadio" function

function getSelectedRadioValue(buttonGroup) {
   // returns the value of the selected radio button or "" if no button is selected
   var i = getSelectedRadio(buttonGroup);
   if (i == -1) {
      return "";
   } else {
      if (buttonGroup[i]) { // Make sure the button group is an array (not just one button)
         return buttonGroup[i].value;
      } else { // The button group is just the one button, and it is checked
         return buttonGroup.value;
      }
   }
} // Ends the "getSelectedRadioValue" function
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜