开发者

clear file input field using jQuery [duplicate]

This question already has answers here: Closed 11 years ago.

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..


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/


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

$('#myform')[0].reset();


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

 var id=$(this).attr('id');
    $(this).replaceWith("<input type='file' id='"+id+"' />");


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

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜