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
omega
  • 40,311
  • 81
  • 251
  • 474

2 Answers2

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.net/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.net/frrc7bLy/

Simon C
  • 9,458
  • 3
  • 36
  • 55
0

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.

  • Well, _this_ and _that_ selector do the same thing. – Ram Feb 08 '15 at 20:25
  • So you're saying that jQuery IS forgiving in that respect? –  Feb 08 '15 at 20:34
  • That's not an invalid selector, both are valid. Quotations are useful when the attribute's value can break the selector/confuse the jQuery's selector engine. An example: `'input[name="group[withBrackets]"]'`. – Ram Feb 08 '15 at 20:37