【问题标题】:jQuery detect empty form how to? [duplicate]jQuery检测空表单如何? [复制]
【发布时间】:2012-10-30 18:05:07
【问题描述】:

可能重复:
empty field validation in jquery

我需要检测表单是否为空。我已经进行了客户端验证,有必填字段而不是必填字段,当有一个或多个必填字段时,这是(这些是)空的,发布按钮会启动客户端验证错误,这很好。当它们都不是强制性的时,我只需要禁用发布按钮,直到我插入一个值,当我写东西时启用发布按钮。但是如果我删除这些值,我无法检测表单是否为空或不重新禁用按钮!

$('#form .my_field').each(function() {
    $(this).data('oldVal', $(this).val());

    $(this).bind("propertychange keyup input paste change blur", function(event) {
        if ($(this).data('oldVal') != $(this).val()) {
            $('#post_button').button({
                disabled: false
            });
        }
    });
});

通过这个绑定,我可以检测到我何时在一个随意的表单字段中写入,但我不知道如何查找每个字段是否都是干净的。我尝试了很多条路,但它们把我引向了死胡同。也许是一个 10 小时的编程问题 :) 我尝试过某种

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

,但是对于某些字段(例如数据选择器)不起作用(我可以选择过多的多选 ----> :option selected)

我想我必须将相同的事件绑定到一个(如果为空,则设置一个布尔标志)并检查所有布尔标志以确定它们是否都是真(或假)..任何提示?

【问题讨论】:

标签: jquery jquery-ui validation


【解决方案1】:

为什么不直接使用else if

演示:http://jsfiddle.net/dfAtX/

jQuery:

$('#form .my_field').each(function() {
    $(this).data('oldVal', $(this).val());

    $(this).bind("propertychange keyup input paste change blur", function(event) {

        if ($(this).data('oldVal') != $(this).val()) {
            $('#post_button').button({
                disabled: false
            });
        }
        else if ($(this).val() == $(this).data('oldVal')) { // Don't even bother checking the rest if this doesn't match
            var unchanged = 0;
            $('#form .my_field').each(function() {
                if ($(this).val() == $(this).data('oldVal')) {
                    unchanged++;
                }
            });

            if (unchanged == $('#form .my_field').length) {
                $('#post_button').button({
                    disabled: true
                });
            }
        }
    });
});​

【讨论】:

  • 只有两件事..我不得不使用'$('#post_button').button({ disabled: true or false });'而不是 jsfiddle attr ..(它不起作用)并且通过一些控制台日志我发现了我的代码中的其他错误,我调用了两次事件,然后不变的值是不可预测的,将表单启动器替换为 on 和 no更多重复事件!!谢谢!你让我今天一整天都感觉很好! :)
  • 对不起,我没有声誉可以标记为好..但我会尽我所能:)
猜你喜欢
  • 2014-04-10
  • 2014-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-09
  • 2013-12-15
  • 2023-03-26
  • 1970-01-01
相关资源
最近更新 更多