繁体   English   中英

我的 function 验证表单中的复选框不适用于 jquery

[英]my function to validate a checkbox in a form not working with jquery

检查术语 function 无法使用 jQuery 验证 HTML 表单中的复选框...

这是我的代码,单击复选框并单击外部以触发验证:

 function check_term() { var term = $("#term").val() if (term.checked = true) { $("term_error_message").hide(); } else { $("term_error_message").html("Please accept our terms and conditions"); $("term_error_message").show(); error_term = true; } console.log("error_term is " + error_term); } $("#term_error_message").hide() var error_term = false; $("#term").focusout(function() { check_term() });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <input id="term" type="checkbox"> I Accept the terms and conditions </div> <div id="term_error_message"></div>

在您的 if 语句中,您将值true分配给term.checked 您应该使用===比较运算符而不是=

像这样: if (term.checked === true) {

我不知道这是否能解决你所有的问题,但这是一个开始。

访问此链接了解更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Comparison

考虑以下。

function check_term() {
  var term = $("#term");
  if (term.prop("checked")) {
    $("#term_error_message").hide();
  } else {
    $("#term_error_message").html("Please accept our terms and conditions");
    $("#term_error_message").show();
  }
  return term.prop("checked");
}

var error_term = false;
$("#term_error_message").hide()
$("#term").blur(function() {
  error_term = check_term();
});

分配#term的值会给你一个字符串,而不是 Object。 因此, term.checked将是undefined 您将需要检查复选框的属性以查看它是否已选中。 .prop() ,因为 Getter 将为检查的属性返回truefalse

您还需要在 jQuery 中使用正确的选择器。 我认为您还指blur回调与focusout

您也可以像这样使用.is()

function check_term() {
  if ($("#term").is(":checked")) {
    $("#term_error_message").hide();
  } else {
    $("#term_error_message").html("Please accept our terms and conditions");
    $("#term_error_message").show();
  }
  return $("#term").is(":checked");
}

这也将返回truefalse

暂无
暂无

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

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