最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to clear an input file field in jquery? - Stack Overflow

programmeradmin1浏览0评论

In jquery I am trying to clear a field, but if I do, it throws an error. It does make the field go empty, but also throws an error. How can I fix that?

Thanks

HTML

<input name="file" type="file" accept="image/*">

JS

var input = $("#profile-edit-form").find("input[name=file]");
var fileName = input.val();

if(fileName) { // returns true if the string is not empty
    input.replaceWith(input.val('').clone(true));
}

ERROR

NotFoundError: Node was not found                  
-jquery.min.js:3:0

In jquery I am trying to clear a field, but if I do, it throws an error. It does make the field go empty, but also throws an error. How can I fix that?

Thanks

HTML

<input name="file" type="file" accept="image/*">

JS

var input = $("#profile-edit-form").find("input[name=file]");
var fileName = input.val();

if(fileName) { // returns true if the string is not empty
    input.replaceWith(input.val('').clone(true));
}

ERROR

NotFoundError: Node was not found                  
-jquery.min.js:3:0
Share Improve this question asked Feb 8, 2015 at 20:06 omegaomega 44k90 gold badges285 silver badges522 bronze badges 1
  • Can you reproduce the error or provide more context? – Ram Commented Feb 8, 2015 at 20:13
Add a ment  | 

2 Answers 2

Reset to default 5

Why are you trying to do a clone?

Just doing this should clear the field:

input.val('');

Here is a fiddle to demonstrate:

http://jsfiddle/kcbc701c/

Edit:

Yeah, there may be issues with the above in older browsers, it'd be worth testing, but for me that works in modern browsers, whereas the other option you stated doesn't work in firefox...

here's a fiddle with both so you can test: http://jsfiddle/frrc7bLy/

Although jQuery might be forgiving enough to handle it, the documented format is:

var input = $("#profile-edit-form").find('input[name="file"]');

Note the quotes around "file" in the selector.

发布评论

评论列表(0)

  1. 暂无评论