【问题标题】:How to check whether a checkbox is checked?如何检查复选框是否被选中?
【发布时间】:2019-01-12 00:14:28
【问题描述】:

这是我现在拥有的东西: 我有一个复选框,我需要验证它是否被选中。

<input type="checkbox" name="person_info_check" value="0" &nbps>Read and agree!</input>

但是当我尝试使用我在互联网上搜索的方式时,我发现我无法抓住复选框并因此验证。

这就是我抓取复选框的方式:

        if($('#person_info_check').is(':checked')){
            if(confirm("Are you sure to submit?")){
                return true;
            }
            else return false;
        }
        else{
            alert("Please read the file and agree the statement!");
            return false;
        }

我也试过这个:

        var checkbox = document.getElementsByName("person_info_check");

        if(checkbox[0].checked==false){
            alert("Please read the file and agree the statement!");
            return false;
        }

【问题讨论】:

  • &amp;nbps 应该是什么?
  • 您的confirm(...") 缺少开场白

标签: javascript jquery checkbox forms


【解决方案1】:

您正在使用$('#person_info_check'),这实际上是一个 jQuery ID Selected,而在您的 HTML 中您指定了 name="person_info_check",因此您的元素没有被选中。

尝试在您的复选框元素中指定id="person_info_check"。大多数 jQuery 代码应该可以工作。

或者您可以使用 JQuery 名称选择器。

$("input[value='person_info_check]")

【讨论】:

    【解决方案2】:

    问题在于 person_info_check 不是您输入的 id 而是 name 属性。你应该使用这个: $("input[name='person_info_check']").is(':checked');

    【讨论】:

      【解决方案3】:

      您的代码中存在重大错误,例如:

      1. 输入类型checkbox不需要任何值标签
      2. 输入类型不需要有结束标签
      3. 输入类型不能处理 HTML 文本;它只能根据标签类型具有值或检查状态。

      输入标签的更多细节可以找到here。代码示例如下:

      var checkbox = document.getElementById("che");
      
      if (checkbox.checked == true) {
        alert('I am checked')
      }
      &lt;input type="checkbox" name="person_info_check" id='che' checked/&gt; &lt;label for='che'&gt;I am checkbox&lt;/label&gt;

      【讨论】:

        猜你喜欢
        • 2021-07-16
        • 1970-01-01
        相关资源
        最近更新 更多