【问题标题】:Check if inputs are empty using jQuery before submitting在提交之前使用 jQuery 检查输入是否为空
【发布时间】:2015-01-27 20:04:13
【问题描述】:

我有一个表单,我希望填写所有字段。如果单击某个字段然后未填写,我想显示引导程序有警告类。

这是我的代码:

$('#registration-form input').blur(function()
{
    if( !$(this).val() ) {
        $(this).parents('li').addClass('has-warning');
    }
});

我做错了什么?

这里是 jsfiddle http://jsfiddle.net/f7gsgy93/

【问题讨论】:

  • 预期的行为是什么?
  • @Ionica 应用引导程序有警告类,它给输入一个红色边框
  • 你也可以提供HTML吗?也许是一个 JSFiddle?
  • 该代码是否正在等待 DOM 准备就绪?

标签: jquery validation


【解决方案1】:

您必须在表单上捕获submit 事件。如果输入无效,则阻止默认行为。

$("form").on("submit", function () {
    var isInvalid = false;
    $("input", this).each(function () {
        if (!$(this).val()) {
            isInvalid = true;
        }
    });
    if (isInvalid) {
        return false;
    }
});

如果你只需要捕捉模糊事件,那就去做吧!

$(document).ready(function() {
  var $error = $(".alert-danger");
  $("form input").on("blur", function() {
    if (!$(this).val()) {
      $error.removeClass("hide").text("No value");
    } else {
      $error.addClass("hide");
    }
  });
});
@import url("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <form action="">
    <input type="text" class="form-control" placeholder="Text input">
    <div class="errors">
      <div class="alert alert-danger hide"></div>
    </div>
  </form>
</div>

【讨论】:

  • 我不想提交。如果我点击一个文本字段,然后如果你点击它,它将验证它是否为空白
  • @CamSonaris 查看编辑。请注意,当您添加偶数侦听器时,您必须确保页面上存在元素。
【解决方案2】:
$('#registration-form input').blur(function() {

    if ($(this).val() == '') {

        $(this).parents('li').addClass('has-warning');

    }

});

【讨论】:

  • 这没有意义,因为!""true
  • 这有什么不妥之处?如果活动输入的值为空,那么它将应用该类。
  • 这也不起作用。在调试器中,它似乎永远不会命中 if 语句
  • 发布相关的 HTML 并确保包含 jQuery,因为如果选择器正确,这应该可以工作。
猜你喜欢
  • 1970-01-01
  • 2011-08-18
  • 2010-12-23
  • 2014-07-30
  • 1970-01-01
  • 1970-01-01
  • 2017-06-30
  • 2012-05-18
  • 2018-04-21
相关资源
最近更新 更多