开发者

Triggering change event on file input when invoked from javascript (ie headache)

I don't know what I'm doing wrong. I've found fixes/hacks for this but none of them seem to be working. Trying to use a single button/image (something) instead of the input-file control. It works so far except for in internet explorer. In ie the 'select file' dialog appears, lets you choose a file, the accompanying textbox gets populated but the change event doesn't fire. I've tried focus, blur, live, onpropertychange, change, onchange... but they just won't work. Any help?

jQuery:

      $(fu开发者_如何转开发nction() {
            var a = $('a.#LinkUpload');
            var f = $('input.#file');
            a.click(function() {
                f.click();
            });
            f.change(function() {
                alert('changed!');
            });
        });

html:

    <body>
    <form action="">
        <div>
            <a id="LinkUpload">Click Me!</a>
            <input type="file" id="file" name="file" />
        </div>
    </form>
</body>


@Pointy said it. If it's an ID, you don't need to specify the tag name, so just do something like:

var $a = $('#LinkUpload'),
    $b = $('#file');

It's also a good practice to add a $ (dollar sign) in your variable names when you're caching a jQuery object, just so you know that a variable is actually a jQuery object.


Here's a slightly cleaner implementation of the file part of Oppdal's solution:

f.bind(($j.browser.msie && $j.browser.version < 9) ? 'propertychange' : 'change',
       function(){ 
           alert('changed!');
       });


It has been changed in the new jQuery version. I updated from 1.4.4 to 1.6.2 and it works fine without the workaround.


Got it! (I think).

$(function() {
    var a = $('#LinkUpload');
    var f = $('#file');
    a.click(function() {
        f.click();
        setTimeout(function() {
            f.val(f.val());
        }, 1);
    });
    if ($.browser.msie && $.browser.version < 9) {
        f.bind('propertychange', function() {
            alert('changed');
        });
    } else {
        f.change(function() {
            alert('changed!');
        });
    }
});

Seems to work.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜