繁体   English   中英

jquery 如何使复选框始终处于选中状态

[英]jquery how to make checkbox always checked

如何使用 Jquery 1.4.2 始终选中复选框?

这是我的 html output 来自 struts 应用程序:

<input type="checkbox" name="helloThere" value="on">

我试过了:

$(document).ready(function() {
    $('#helloThere').attr('checked', 'checked');
});



小提琴

http://jsfiddle.net/96p4zg9w/这显示了当前代码,我需要复选框加载选中。

props 属性在 JQUERY 1.4.2 中不可用

您的jQuery选择器是错误的。

您正在尝试选择具有'helloThere'ID的元素,但您的输入没有id属性。 您可以将此属性添加到输入字段或更改jquery选择器。

尝试以下两种解决方案之一:

<input type="checkbox" name="helloThere" id="helloThere" value="on">

要么

$(document).ready(function() {
    $("input[name='helloThere']").attr('checked', 'checked');
});

您需要将JavaScript放入$(document).ready() 这样可以确保在尝试更改内容之前,您可能要触摸的所有内容均已加载。

那么在您的方案中,您将需要:

$(document).ready(function() {
    $('#helloThere').attr('checked', 'checked');
});

编辑 :您的复选框没有ID。 您需要为$('#helloThere')添加ID“ helloThere”, $('#helloThere')进行提取。 您的小提琴还需要使用左侧菜单加载jQuery。 这是一个工作版本: http : //jsfiddle.net/96p4zg9w/1/

查看此jsfiddle ,了解如何使用javascript进行工作的示例。 如果要使用低于1.5的jQuery版本,则需要采用以下方式:

$("#checkbox").attr("checked", true);

要么

$("#checkbox").attr("checked", "checked");

如果要使用名称而不是ID选择元素,请使用:

input[name='helloThere']

希望它有用!

它可以通过三种方式完成。 您可以使用签入输入,该输入将始终保持选中状态。

<input id="myId" type="checkbox" name="name" checked>

使用prop并假设输入id为myId

 $(document).ready(function() {
     $(#myId).prop('checked', true);
 });

在jQuery 1.6之前使用attr

 $(document).ready(function() {
     $(#ID).attr('checked','checked');
 });

 <lable>this will always be checked, even you try to uncheck</lable>: <input type="checkbox" checked onclick="return false;">

暂无
暂无

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

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