2

Possible Duplicate:
Blank out a form with jQuery

I am using a jQuery function to clear all my form values.

$.fn.clearForm = function() {
  return this.each(function() {
    var type = this.type, tag = this.tagName.toLowerCase();
    if (tag == 'form')
      return $(':input',this).clearForm();
    if (type == 'text' || type == 'password' || tag == 'textarea')
      this.value = '';
    else if (type == 'checkbox' || type == 'radio')
      this.checked = false;
    else if (tag == 'select')
      this.selectedIndex = -1;
  });
};

the problem with above function is it does not reset the file input field. is there anyway i could extend the function and make it to work with clearing file input field as well.

here is file input field HTML code i am using.

<section><label for="productimg">Picture<br></label>
    <div><input type="file" id="productimg" name="productimg"></div>
</section>

thank you..

Community
  • 1
  • 1
Ibrahim Azhar Armar
  • 25,288
  • 35
  • 131
  • 207

5 Answers5

12

Try using the form reset, to get back to the initial values -

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

Demo - http://jsfiddle.net/hPytd/ & http://jsfiddle.net/hPytd/1/

Jayendra
  • 52,349
  • 4
  • 80
  • 90
2

You can call the native reset() method on the form element:

$('#myform')[0].reset();
Sjoerd
  • 74,049
  • 16
  • 131
  • 175
2

You can replace the file input with html to do this,

 var id=$(this).attr('id');
    $(this).replaceWith("<input type='file' id='"+id+"' />");
Jayantha Lal Sirisena
  • 21,216
  • 11
  • 71
  • 92
0

Have you ever try adding the type file to the validation,like this:

if (type == 'text' || type == 'password' || tag == 'textarea' || type == 'file')

Allende
  • 1,480
  • 2
  • 22
  • 39
0

Depending on the full scope there are multiple methods to accomplish your desired result and they are much easier than you probably think:

  1. Use <input type="reset" /> to reset your form
  2. Build a .reset() function in jQuery:

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

NOTE: Method 2 does work as it is a native JavaScript function.

Robert
  • 8,717
  • 2
  • 27
  • 34