使用javascript检查单选按钮 [英] Check a radio button with javascript
问题描述
由于某些原因,我似乎无法找出这一点。
我的HTML中有一些单选按钮,可以切换类别:
< input type =radioname =main-categoriesid =_ 1234value =1234/> // All
< input type =radioname =main-categoriesid =_ 2345value =2345/> //某些类别
< input type =radioname =main-categoriesid =_ 3456value =3456/> // certain category
< input type =radioname =main-categoriesid =_ 4567value =4567/> //某些类别
用户可以选择他/她想要的,但是当某个事件触发时,我想将 1234
设置为选中单选按钮,因为这是默认选中的单选按钮。
I尝试过这个版本(有和没有jQuery):
document.getElementById('#_ 1234')。checked = true;
但它似乎没有更新。我需要它明显更新,以便用户可以看到它。
任何人都可以帮助吗?
编辑:我只是累了,忽略了#
指出它,并且 $。prop()
。
为什么使用 all
而不是 id
也不要将CSS语法(#
)用于原生JS
Native JS解决方案:
document.getElementById(_ 1234)。checked = true;
JQuery解决方案: b
$ b
$(#_ 1234)。prop(checked,true);
For some reason, I can't seem to figure this out.
I have some radio buttons in my html which toggles categories:
<input type="radio" name="main-categories" id="_1234" value="1234" /> // All
<input type="radio" name="main-categories" id="_2345" value="2345" /> // Certain category
<input type="radio" name="main-categories" id="_3456" value="3456" /> // Certain category
<input type="radio" name="main-categories" id="_4567" value="4567" /> // Certain category
The user can select whichever he/she wants, but when an certain event triggers, I want to set 1234
to be set checked radio button, because this is the default checked radio button.
I have tried versions of this (with and without jQuery):
document.getElementById('#_1234').checked = true;
But it doesn't seem to update. I need it to visibly update so the user can see it. Can anybody help?
EDIT: I'm just tired and overlooked the #
, thanks for pointing it out, that and $.prop()
.
Why do you use
all
instead ofid
value?Also do not mix CSS syntax (
#
for identifier) with native JS
Native JS solution:
document.getElementById("_1234").checked = true;
JQuery solution:
$("#_1234").prop("checked", true);
这篇关于使用javascript检查单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!