Check a radio button with javascript(使用 javascript 检查单选按钮)
问题描述
由于某种原因,我似乎无法弄清楚这一点.
For some reason, I can't seem to figure this out.
我的 html 中有一些单选按钮可以切换类别:
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
用户可以选择任何他/她想要的,但是当某个事件触发时,我想设置 1234
设置为选中单选按钮,因为这是默认选中单选按钮.
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.
我已经尝试过这个版本(有和没有 jQuery):
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?
我只是累了,忽略了 #
,感谢您指出它和 $.prop()
.
I'm just tired and overlooked the #
, thanks for pointing it out, that and $.prop()
.
推荐答案
不要将 CSS/JQuery 语法(#
表示标识符)与原生 JS 混合.
Do not mix CSS/JQuery syntax (#
for identifier) with native JS.
原生 JS 解决方案:
document.getElementById("_1234").checked = true;
jQuery 解决方案:
$("#_1234").prop("checked", true);
这篇关于使用 javascript 检查单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 javascript 检查单选按钮


基础教程推荐
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01