当有多个表单时,需要创建一个字段

时间:2013-10-07 20:00:31

标签: jquery required-field

我有一个包含多个表单的页面。我可以通过

模拟必填字段
$('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;
    }

});

但是,如果页面上有多个表单,并且其中一个表单具有必填字段,则其他表单会受到影响。

3 个答案:

答案 0 :(得分: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 '的范围采取行动,这是你提交的绑定表单元素,然后* 找到 * ing a输入和textarea标签

答案 1 :(得分:0)

改变这个:

empty_fields = $('form#'+formId+' input, textarea').filter(function(){...});

答案 2 :(得分: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;
    }

});