javascript 如何在没有表单的情况下制作复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6049430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:17:05  来源:igfitidea点击:

How to make a checkbox without a form

javascriptjqueryhtml

提问by Stanley Cup Phil

I have been trying to make a simple app with 3 fields like this:

我一直在尝试制作一个包含 3 个字段的简单应用程序,如下所示:

    <div id = "nameInput" >Name:</div><input id = "nameInputField" type = "text" name = "userName" />
    <div id = "emailInput" >Email:</div><input id = "emailInputField" type = "text" name = "email" />
    <input id = "termsCheck" type = "checkbox" name = "terms" />

The problem I am having is that I keep needing to try to wrap it in a form to get the checkbox to register as checked when it is. I DO NOT want to use a form because I don't ever want to submit anything.

我遇到的问题是我一直需要尝试将它包装在一个表单中,以使复选框在选中时注册为选中状态。我不想使用表单,因为我不想提交任何东西。

Here is the JS for the checkbox as well. It is always marked as unchecked:

这里也是复选框的JS。它始终标记为未选中:

if ($('#terms').checked == true) {
    //Rest of code

Is there a way to make this without using a form or is there a reason that my checkbox is never registered as checked?

有没有办法在不使用表单的情况下做到这一点,或者是否有原因我的复选框从未注册为选中状态?

回答by Naftali aka Neal

<input id = "termsCheck" type="checkbox" name="terms" />

JS:

JS:

pre jQuery 1.6:

jQuery 1.6 之前:

if($('#termsCheck').is(':checked')){}

after jQuery 1.6:

在 jQuery 1.6 之后:

if($('#termsCheck').prop('checked')){}

回答by user113716

Two issues.

两个问题。

First, you're referencing the name of the input instead of its ID.

首先,您引用的是输入的名称而不是其 ID。

Second, in order to use the checkedproperty, it must be done on the DOM element, not the jQuery object.

其次,为了使用checked属性,它必须在 DOM 元素上完成,而不是在 jQuery 对象上。

if( $('#termsCheck')[0].checked ) {
    // ...
}

This is accessing the DOM element at index 0of the jQuery object, then accessing its checkedproperty.

这是访问0jQuery 对象索引处的 DOM 元素,然后访问其checked属性。

You could also use the get()[docs]method to retrieve the DOM element.

您还可以使用get()[docs]方法来检索 DOM 元素。

if( $('#termsCheck').get(0).checked ) {
    // ...
}

回答by Tim Erickson

If you DON'T want to use jQuery, you could do something like:

如果您不想使用 jQuery,您可以执行以下操作:

<input id = "termsCheck" type = "checkbox" name = "terms" />

and refer to it this way:

并以这种方式引用它:

if (document.getElementById("termsCheck").checked) {
}

回答by megakorre

the jquery object (witch im asuming your using) dosent have an checked field so that fill be false yes

jquery 对象(假设您使用的女巫)没有一个选中的字段,因此填充为 false 是

what you can do is

你能做的是

 $("#terms").is(":checked")

回答by hunter

You need to check the checked state differently

您需要以不同的方式检查选中状态

$('#terms').is(":checked")