4

Possible Duplicate:
IE 9 jQuery not setting input value

I would like to reset the input field if it matches some conditions using $(this).val("");:

$(".checkimgextension").on("change", function () {

var file = $(this).val();

if (some conditions){
  alert("wrong:...");
  $(this).val("");
}   

With Firefox the field is set to "", but with IE the field does not change as expected. Am using the right function .val("")?

4
  • Works fine for me in IE: jsfiddle.net/xNsEZ/1
    – Chad
    Commented Dec 6, 2012 at 14:14
  • Fiddle, or it didn't happen.
    – moonwave99
    Commented Dec 6, 2012 at 14:14
  • 2
    In your title, you say "file" -- you mean really mean input type="file"? Commented Dec 6, 2012 at 14:14
  • 1
    Guys it's very likely to be a "file" input, and you can't set its value from JavaScript in IE.
    – Pointy
    Commented Dec 6, 2012 at 14:15

1 Answer 1

8

Refer to this: IE 9 jQuery not setting input value

$("input[type='file']").replaceWith($("input[type='file']").clone(true));

So in your case:

$(this).replaceWith($(this).clone(true));

instead of the $(this).val(""); line.

UPDATE:

In order to take advantage of browsers that allow you to modify the input:file element, I would use something like this:

$(".checkimgextension").on("change", function () {
    var $this = $(this);

    if (some conditions) {
        alert("wrong:...");
        $this.val("");
        var new_val = $this.val();
        if (new_val !== "") {
            $this.replaceWith($this.clone(true));
        }
    }
});

That way, it attempts to just set the value to empty at first, and if that doesn't succeed, use the replaceWith method.

1
  • Updated to avoid replaceWith when possible
    – Ian
    Commented Dec 6, 2012 at 17:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.