Reset Form with JQuery

with 3 comments

When you submit form using Ajax (JQuery) then success, you have to reset form using javascript after submited. Reset button maybe doesn’t helpful in this condition. So you need a JQuery reset function to reset form.

  1. $('#form_add').submit(function() {
  2.     $.ajax({
  3.         type: $(this).attr('method'),
  4.         url: $(this).attr('action'),
  5.         dataType: 'json',
  6.         data: $(this).serialize(),
  7.         success: function(data) {
  8.             if(data[0]== "true"){ //success
  9.                 //call function to reset form
  10.                 $('#form_add')[0].reset();
  11.             }else{ //false
  12.                 alert("Error");
  13.             }
  14.         }
  15.     });
  16.     return false;
  17. });
$('#form_add').submit(function() {
    $.ajax({
        type: $(this).attr('method'),
        url: $(this).attr('action'),
        dataType: 'json',
        data: $(this).serialize(),
        success: function(data) {
            if(data[0]== "true"){ //success
                //call function to reset form
                $('#form_add')[0].reset();
            }else{ //false
                alert("Error");
            }
        }
    });
    return false;
});

Hope this function useful.

Written by Nur Cahya Pribadi

October 8th, 2012 at 10:40 pm

Posted in JQuery,JS Lab

Tagged with , , , ,

3 Responses to 'Reset Form with JQuery'

Subscribe to comments with RSS or TrackBack to 'Reset Form with JQuery'.

  1. $(’#form-id’)[0].reset();

    asd

    15 Oct 12 at 10:57 am

  2. This is definitely not the same behavior as a reset button.
    You do not take into account “checked” attribute, nor “value”.
    Then, your case “textarea” will not work (since textarea is the tag name, not the input type).

    I agree with “asd” for a quick and simple solution, calling native reset().

    Guillaume Poussel

    15 Oct 12 at 2:12 pm

  3. Thank Asd and Guillaume your comments are helpful.

    Senior Labs Assistant

    15 Oct 12 at 3:19 pm

Leave a Reply