简体   繁体   中英

input type=file onchange event is not firing in google chrome/firefox

Update:

http://jsfiddle.net/TmUmG/230/ http //jsfiddle.net/TmUmG/230/




Original question:

I have an image/logo, next to the hidden input type=file:

<form class="image fit" id="theuploadform">
     <input title="click me to change logo" type="image" src="images/sample_image.jpg" style="width:inherit;height:inherit"/>
     <input type="file" id="userfile" name="userfile" style="display:none" />
</form>

idea is on click the image browse for the file, upload it and refresh the original image. My code works in IE, but not in Chrome/FF ((

click handling:

// click for image upload
$("input[type='image']").click(function () {
    $("input[id='userfile']").click();
});

This prompts me to select a file. Upon onchange, I want to submit the form:

    // upload image form 
$("input[id='userfile']").on("change", function() { 
    //alert('here!');
    var iframe = $('<iframe name="postiframe" id="postiframe" style="display: none"></iframe>');

    $("body").append(iframe);

    var form = $('#theuploadform');
    form.attr("action", "/UploadHandler.ashx");
    form.attr("method", "post");
    form.attr("encoding", "multipart/form-data");
    form.attr("enctype", "multipart/form-data");
    form.attr("target", "postiframe");
    form.attr("file", $('#userfile').val());
    form.submit();

    $("#postiframe").load(function () {
        iframeContents = this.contentWindow.document.body.innerHTML;
        $("#textarea").html(iframeContents);

        var filename = $('#userfile').val().replace(/\\/g, '/');
        var fileNameIndex = filename.lastIndexOf("/") + 1;
        filename = filename.substr(fileNameIndex);

        $("input[type='image']").attr("src", "Uploads/" + filename);
    });
    //return false;
});

all above works in IE 9+.

I just found this post: Upload files using input type="file" field with .change() event not always firing in IE and Chrome Not sure yet, but it sounds relevant.

解决方案:对于Firefox,使用“ oninput”而不是“ onchange”。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM