输入复选框默认选中

问题描述 投票:0回答:7

在我的一生中,我无法将我的复选框设置为在页面加载时选中。 我尝试在 id 之后添加

value="true"
Checked="checked"
但仍然没有。有什么想法吗?

<div class="onoffswitch-container">
<span class="onoffswitch-title">Open Inline</span>
<span class="onoffswitch">
<input type="checkbox" class="onoffswitch-checkbox" id="inline"> 
<label class="onoffswitch-label" for="inline">
<span class="onoffswitch-inner" data-swchoff-text="OFF" data-swchon-text="ON"></span>
<span class="onoffswitch-switch"></span>
</label>
 </span>
</div>
html css
7个回答
131
投票

只要写“checked”就可以了

 <input type="checkbox" class="onoffswitch-checkbox" id="inline" checked> 

22
投票

在下面添加了“true”参数,之前尝试一下,它对我有用

<input type="checkbox" class="onoffswitch-checkbox" id="inline" checked="true"> 

8
投票

属性

checked="checked"
确实有效,简写符号就是
checked

<div class="onoffswitch-container">
<span class="onoffswitch-title">Open Inline</span>
<span class="onoffswitch">
<input type="checkbox" class="onoffswitch-checkbox" id="inline" checked="checked"/> 
<label class="onoffswitch-label" for="inline">
<span class="onoffswitch-inner" data-swchoff-text="OFF" data-swchon-text="ON"></span>
<span class="onoffswitch-switch"></span>
</label>
 </span>
</div>


4
投票

我尝试了以上所有解决方案,但没有任何效果。它确实给了我一些术语来继续我的研究。我最终所做的是转到代码底部并添加

$('#inline').prop('checked', true);
这解决了我的问题。


1
投票

您正在寻找

checked
内容属性。以下是官方文档中的相关片段:(生活标准):

checked content 属性是一个布尔属性,它给出输入元素的默认检查状态。添加checked内容属性时,如果控件没有脏检查性,则用户代理必须将元素的checkedness设置为true;当checked内容属性被删除时,如果控件没有脏检查,用户代理必须将元素的checkedness设置为false。

请注意,文档包含相关术语定义的链接。

如果看起来技术性太强,您可以随时访问 checked

 上的 MDN 页面。 MDN 贡献者付出了相当大的努力,将 HTML 标准“翻译”成更易读/更容易理解的形式(通常带有示例),这对于没有扎实的 Web 相关术语和概念基础的人尤其有用。

注意: 您还可以在 MDN 上找到 问题的直接答案


0
投票
 <input type="checkbox" checked /> 

-2
投票

我认为值得补充的是,设置

checked
属性将选中该框,并且不允许用户取消选中它。如果所需的功能是默认选中复选框但用户仍可以取消选中,请使用
defaultChecked
属性:

<input type="checkbox" id="inline" defaultChecked />

document.getElementById("inline").defaultChecked = true;
© www.soinside.com 2019 - 2024. All rights reserved.