发送自定义 jQuery 验证表单

Sending a custom jQuery validation form

本文关键字:验证 表单 jQuery 自定义      更新时间:2023-09-26

我一直在做一些自定义验证(非常基本)。它做了我需要它做的事情,但我无法弄清楚如何提交表格。我以为返回真会起作用,但可悲的是它没有。这是我当前使用的代码。

$('button').click(function() {
    $('.required').each(function() {
        if ($(this).val() == '') {
            return false;
            $(this).val("Please enter a value.");
            $(this).css("background", "#d42c43");
            $(this).css("border-color", "#d42c43");
            $(this).css("color", "#ffffff", "!important");
        } else {
            return true;
        }
    });
});

我希望需要的所有输入字段中都有所需的类。

这里有一个小提琴:http://jsfiddle.net/y5yncmtc/2

$('button').click(function(e) {
    $('.required').each(function() {
       var form = $(e.currentTarget);
           valueToEvaul = $('#valueToEval').val();
        if (valueToEvaul == '') {
            e.preventDefault();
            $(this).val("Please enter a value.");
            $(this).css("background", "#d42c43");
            $(this).css("border-color", "#d42c43");
            $(this).css("color", "#ffffff", "!important");
        } else {
            return true;
        }
    });
});

您可以在表单中添加一个 id,然后在 jQuery 中使用 $('#form_id').submit(); 方法。

由于它不是提交,因此单击时不会提交。

按钮在窗体内,对吧?您可以递归导航到它的父级,直到找到表单标记,然后提交。

$(this).parent().submit();

或者,您可以将按钮替换为提交,其提交与否的行为将由 onclick 的返回来定义。

$('button').click(function() {
    $('.required').each(function(e) {
       e.preventDefault();
      var form = $(e.currentTarget); //the form
           valueToEvaul = form.find('#valueToEval').val(); //the value to evaul
        if (valueToEvaul  == '') {
            $(this).val("Please enter a value.");
            $(this).css("background", "#d42c43");
            $(this).css("border-color", "#d42c43");
            $(this).css("color", "#ffffff", "!important");
        } else {
            return true;
        }
    });
});

只需取下return false