Set radio button 'checked' in jquery based on ID

孤街浪徒 提交于 2019-12-30 17:27:16

问题


I have two radio buttons with the same name, one is checked by default. How can you check or uncheck a radio button in jQuery when selecting from id?

I've tried:

$('#radio1').attr('checked','checked');
$('#radio1').attr('checked', true);

Nothing seems to work.. any ideas?

Thank you!


回答1:


You can not have same id (#radio1) more than once, use a class instead.

$('.radio1').attr('checked', true);
$('.radio2').attr('checked', true);

The id should be used once per element per page.

If you want to check/uncheck on click however, you may do like:

$('#someid').click(function(){
  $('#radio1').attr('checked', true);
});

Or

$('#someid').click(function(){
  $('#radio1').attr('checked', this.checked);
});



回答2:


If you have the radios like:

<input type="radio" id="radio1" name="same-radio-name" />
<input type="radio" id="radio2" name="same-radio-name" />

So, to check the second and uncheck the first one:

$('#radio2').attr('checked', true);

Viceversa:

$('#radio1').attr('checked', true);

Just another thought, are you using the radio as a JQuery UI button? If so you may also need to refresh it like:

$('#radio1').attr('checked', true).button("refresh");



回答3:


Well, if you wanna get a value from the input radio to upload this value from your database you can try with this simple code:

 var selValue = $('input[name=rbnNumber]:checked').val();

Where you put the name of the variable "selValue" and inside of this you specific the name of the radio group "rbnNumber". All this inside the function that you work and done.



来源:https://stackoverflow.com/questions/3121785/set-radio-button-checked-in-jquery-based-on-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!