0

我有一个包含多种表单的页面。我可以通过模拟必填字段

$('form').submit(function () {
    var empty_fields = $('input, textarea').filter(function () {

        //return empty required fields
        return $(this).attr("required") && $(this).val() === "";
    });

    // if empty required field stop the form submitting and let the user know
    if (empty_fields.length) {
        alert('All required fields must have data');
        return false;
    }

});

但是,如果一个页面上有多个表单,其中一个有必填字段,那么其他表单就会受到影响。

4

3 回答 3

4

为什么不使用“ this ”来引用您将提交处理程序绑定到的“form”元素:

$('form').submit(function () {

    var $this = $(this);  // $(this) is the 'form' field tag you binded to

    var empty_fields = $this.find('input, textarea').filter(function () {

       //return empty required fields
       return $(this).attr("required") && $(this).val() === "";
    });

    // if empty required field stop the form submitting and let the user know
    if (empty_fields.length) {
          alert('All required fields must have data');
          return false;
    }
});

所以这样你只对' this '的范围采取行动,这是你绑定提交的表单元素,然后*在其中找到一个输入和textarea标签

于 2013-10-07T20:06:46.150 回答
0

做这个 :

$('form').submit(function () {
    var empty_fields = $('input, textarea').filter(function () {

        //return empty required fields
        return $(this).attr("required") && $(this).val() === "";
    });

    // if empty required field stop the form submitting and let the user know
    if ($(this).hasClass("form1") &&  empty_fields.length) {
        alert('All required fields must have data');
        return false;
    }

});
于 2013-10-07T20:04:01.530 回答
0

改变这个:

empty_fields = $('form#'+formId+' input, textarea').filter(function(){...});
于 2013-10-07T20:02:26.617 回答