开发者

Click trigger on select box doesn't work in jQuery

开发者 https://www.devze.com 2023-01-01 00:31 出处:网络
How can a dropdown list can be opened with a trigge开发者_开发技巧r? Here is the code which doesn\'t work:

How can a dropdown list can be opened with a trigge开发者_开发技巧r?

Here is the code which doesn't work:

$('select').trigger('click');

Just for note - mousedown and mouseup also doesn't work.


$('select').children('option').each(function() {
    if ($(this).is(':selected'))
    { $(this).trigger('change');  }
});


What you are trying to achieve is impossible. Even if you trigger a click the drop down list won't open like if the user clicked on it. If you want to change the currently selected value with a new one you could use the val function. I guess the only solution is to simulate the whole UI look and feel of a select element using divs.


Took me a while but found a solution:

(Chrome & Safari ONLY)

function open(elem) {
    if (document.createEvent) {
        var e = document.createEvent("MouseEvents");
        e.initMouseEvent("mousedown", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        elem[0].dispatchEvent(e);
    } else if (element.fireEvent) {
        elem[0].fireEvent("onmousedown");
    }
}

http://jsfiddle.net/oscarj24/GR9jU/


There is no proper way to click on a dropdown programmatically.

You can either select an option via:

$('#sourceOptions>option:eq(0)').prop('selected', 'selected');

If you want to simulate a user click: you have to do it as @Renso says it:

$('#sourceOptions>option:eq(0)').prop('selected', 'selected').trigger('change');


Instead of trigger give it a size. This simply opens the select (tested in Chrome):

/////// $('select').trigger('click'); $('select')[0].size = 10;

0

精彩评论

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