Search code examples
javascriptjqueryjquery-forms-plugin

Error when I tried to reset an html form


In my current spring project, after I submit a form, I need reset it. I am doing this with this javascript/jquery code:

$('form.form').ajaxForm(function(data) {
    $('form.form').each(function(){
        this.reset();
    });
});

The problem with this code is that some forms have inner forms, opened in a popup windows (which source <div> is placed in the same jsp page). In this case, the code above resets both forms.

I tried this other code:

$('form.form').ajaxForm(function(data) {
    $(this).each(function(){
        this.reset();
    });
});

but with this, I get this error:

Uncaught TypeError: Object #<Object> has no method 'reset'

What's wrong with this second way in comparison with the first one? How I could reset the form then?

UPDATE

following the instruction from this answer, I try this:

jQuery.fn.reset = function () {
      $(this).each (function() { this.reset(); });
};

$('form.form').ajaxForm(function(data) {
    $(this).reset();
});

but still it's happening the same.

UPDATE 2

At last, I try this code:

$('form.form').ajaxForm(function(data) {
    var nome = $('form.form').attr('id');

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

    $('#'+nome).each(function(){
        this.reset();
    });
});

which reset only the main form (the first one to be opened). I wonder if there is a solution to reference the last opened form (the one opened inside the jquery-ui dialog <div>).


Solution

  • I finally find a solution for this issue, with this code:

    $('form.form').each(function () {
        var form = this;
        $(form).ajaxForm(function (data) {
            if (data == '') {
                $(form).find('#yes').css('display', 'block');
            } else {
                $(form).find('#not').css('display', 'block');
            }
            form.reset();
        });
    });
    

    following the instructions from this answer: https://stackoverflow.com/a/25173296/2692962