用 javascript 检查单选按钮

不知道为什么,我好像想不通。

我的 html 中有一些单选按钮可以切换类别:

<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为设置选中单选按钮,因为这是默认的选中单选按钮。

我已经尝试过这样的版本(有和没有 jQuery) :

document.getElementById('#_1234').checked = true;

但它似乎没有更新。我需要它可见的更新,以便用户可以看到它。 有人能帮忙吗?

编辑: 我只是累了,忽略了 #,谢谢你指出来,那个和 $.prop()

452341 次浏览

如果你想设置“1234”按钮,你需要使用它的“ id”:

document.getElementById("_1234").checked = true;

在使用浏览器 API (“ getElementById”)时,不使用选择器语法; 只传递要查找的实际“ id”值。在 jQuery 或 .querySelector().querySelectorAll()中使用选择器语法。

不要将 CSS/JQuery 语法(标识符为 #)与本机 JS 混合使用。

原生 JS 解决方案:

document.getElementById("_1234").checked = true;

JQuery 解决方案:

$("#_1234").prop("checked", true);

通过使用 document.getElementById()函数,您不必在元素的 id 之前传递 #

密码:

document.getElementById('_1234').checked = true;

演示: JSFiddle

最简单的方法可能是使用 jQuery,如下所示:

$(document).ready(function(){
$("#_1234").attr("checked","checked");
})

这将添加一个新的属性“ check”(在 HTML 中不需要值)。 只要记住包含 jQuery 库:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

今天,在2016年,使用 document.querySelector而不知道 ID 是安全的(特别是如果你有两个以上的单选按钮) :

document.querySelector("input[name=main-categories]:checked").value

通过使用 Firefox 72中的 Javascript 代码,我可以选择(检查)一个单选输入按钮,在 Web 扩展选项页面中 LOAD 值:

var reloadItem = browser.storage.sync.get('reload_mode');
reloadItem.then((response) => {
if (response["reload_mode"] == "Periodic") {
document.querySelector('input[name=reload_mode][value="Periodic"]').click();
} else if (response["reload_mode"] == "Page Bottom") {
document.querySelector('input[name=reload_mode][value="Page Bottom"]').click();
} else {
document.querySelector('input[name=reload_mode][value="Both"]').click();
}
});

其中与 SAVE 关联的代码的值为:

reload_mode: document.querySelector('input[name=reload_mode]:checked').value

给定如下 HTML:

    <input type="radio" id="periodic" name="reload_mode" value="Periodic">
<label for="periodic">Periodic</label><br>
<input type="radio" id="bottom" name="reload_mode" value="Page Bottom">
<label for="bottom">Page Bottom</label><br>
<input type="radio" id="both" name="reload_mode" value="Both">
<label for="both">Both</label></br></br>

HTML 单选按钮的 item.check 属性似乎不能用 JavaScript 在 Internet Explorer 中或在一些较老的浏览器中进行更改。

我还尝试设置“ check”属性,使用: 我知道默认情况下可以设置属性, 但是我只需要在运行时更改选中的属性。

作为一种变通方法,我找到了另一种可行的方法。我调用了单选按钮的 item.click();方法。控件已被选中。但是控件必须已经添加到 HTML 文档中,才能接收 click 事件。