我使用名称和文本填写了此输入表单。

<form action="" method="post" class="main">
    <label>Write a comment!</label><br>
    <input placeholder="Name" class="form-text" name="user" type = "text" id = "user" autofocus size = "48"><br/>
    <textarea class="form-text" name="comment" id="comment" placeholder="Text"></textarea>
    <br />
    <input type="submit" class="form-submit" name="new_comment" value="Submit comment">
</form>


我为此表格添加了jQuery

$(".form-submit").click(function() {
    var commentBox = $("#comment");
    var userBox = $("#user");

    var commentCheck = commentBox.val();
    var userCheck = userBox.val();

    if(commentCheck == '' || commentCheck == NULL ) {
        commentBox.addClass("form-text-error");
        console.log(commentBox);
        return false;
    }

    if (userCheck == '' || userCheck == NULL){
        userBox.addClass("form-text-error");
        console.log(userBox);
        return false;
    }
});


现在我遇到了这个问题。我希望用户填写两个字段才能写评论(name & text)。对于任何空字段,我想添加类"form-text-error"。一切正常,除了带有用户名的字段。

有什么建议么?

最佳答案

使用Length获得input的长度,然后如果返回零,则执行addClass



$(".form-submit").click(function() {
  var commentBox = $("#comment");
  var userBox = $("#user");

  var commentCheck = commentBox.val();
  var userCheck = userBox.val();



  if (commentCheck.length <= 0 || commentCheck == NULL) {
    commentBox.addClass("form-text-error");
    console.log(commentBox);
    return false;
  }

  if (userCheck.length <= 0 || userCheck == NULL) {
    userBox.addClass("form-text-error");
    console.log(userBox);
    return false;
  }



});

.form-text-error {
border: 1px solid red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" class="main">
  <label>Write a comment!</label><br>
  <input placeholder="Name" class="form-text" name="user" type="text" id="user" autofocus size="48"><br/>
  <textarea class="form-text" name="comment" id="comment" placeholder="Text"></textarea>
  <br />
  <input type="submit" class="form-submit" name="new_comment" value="Submit comment">
</form>





您也可以使用submit函数代替click

$(".form-submit").submit(function() {});


但我建议您使用这样的方法:

$(".form-submit").click(function(e) {
  e.preventDefault(); //remove this later
  $('.form-text').each(function() {
    if ($(this).val().length <= 0) {
      $(this).addClass('form-text-error');
      return false;
    } else {
      $(this).removeClass('form-text-error');
      return true;
    }
  });
});

10-04 22:56