Handling multiple forms in the same page

2019-08-05 10:36发布

问题:

If I have something like this in some page in my project:

<div class="dialog" title="Basic dialog" id="popup">
    <div class="text"> </div>
</div>

<c:url value="/${entity}/cadastra" var="cadastra"/>
<form:form method="POST" action="${cadastra}" class="form" enctype="multipart/form-data">
...
    <button type="submit" class="btn btn-lg btn-primary">cadastrar</button>
</form:form>

and the submit event is handled by this code:

$('form.form').ajaxForm(function(data) {
    if(data == '')
        $('#yes').css('display', 'block');
    else
        $('#not').css('display', 'block');

    $('<<element>>').each(function(){
        this.reset();
    });
});

anyone knows what should be the value for <> if I want reset only the fields from the form I submit, and I could have a new form, with the same class, inside div.dialog?

If I use form.form both forms are reseted, and if I use this, I get an error. Any ideas to solve this?

回答1:

Whenever you are uncertain about access to elements within a plugin you can always initialize them individiually within an each loop.

Within each this will be the element instance and you can store it as variable to pass into plugin.

$('form.form').each(function () {
    /* assign "this" to variable that can be used inside plugin */
    var form = this;
    $(form).ajaxForm(function (data) {
        if (data == '') {
            $('#yes').css('display', 'block');
        } else {
            $('#not').css('display', 'block');
        }
        form.reset();
    });
});