繁体   English   中英

使用 javascript 检查单选按钮

[英]Check a radio button with 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()

不要将 CSS/JQuery 语法( #表示标识符)与原生 JS 混合。

原生 JS 解决方案:

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

jQuery解决方案:

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

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

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

当您使用浏览器 API(“getElementById”)时,您不使用选择器语法; 您只需传递您正在寻找的实际“id”值。 您可以将选择器语法与 jQuery 或.querySelector().querySelectorAll()一起使用。

今天,在 2016 年,在不知道 ID 的情况下使用document.querySelector是安全的(尤其是如果您有超过 2 个单选按钮):

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

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

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

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

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

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

代码:

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

演示: JSFiddle

我能够通过在 Firefox 72 中使用此 Javascript 代码在 Web 扩展选项页面中选择(检查)单选输入按钮以加载值:

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();
    }
});

保存该值的相关代码是:

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.checked 属性无法在 Internet Explorer 或某些较旧的浏览器中使用 JavaScript 进行更改。

我还尝试设置“checked”属性,使用: item.setAttribute("checked", ""); 我知道该属性可以默认设置,但我只需要在运行时更改选中的属性。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM