Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

javascript - How to open select element using jquery

I have a select element as follows. i want to open it without user having to click on it.

    <select id="selId" class="pos_fixed">
       <option value="volvo">Option1</option>
       <option value="saab">Option2</option>
       <option value="mercedes">Option3</option>
       <option value="audi">Option4</option>
    </select>

Please let me know if its possible using jquery or javascript

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You will pass a CSS selector to openSelect() and it will open the select element for you.

var openSelect = function(selector){
     var element = $(selector)[0], worked = false;
    if (document.createEvent) { // all browsers
        var e = document.createEvent("MouseEvents");
        e.initMouseEvent("mousedown", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        worked = element.dispatchEvent(e);
    } else if (element.fireEvent) { // ie
        worked = element.fireEvent("onmousedown");
    }
    if (!worked) { // unknown browser / error
        alert("It didn't worked in your browser.");
    }   
}

$(function(){ // when DOM is ready
   // open .select element
   openSelect('.select'); 
});

Here's a fiddle: http://jsfiddle.net/Z48wF/1/

Source: How to open the select input using jquery @stackoverflow.com


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...