How to open the select input using jquery

后端 未结 3 1957
一个人的身影
一个人的身影 2020-11-29 08:53

So I can see the options of the select element but I need to click on it. What if I want to use a function? When something happens this select element should be selected, me

相关标签:
3条回答
  • 2020-11-29 09:20

    I dont think you can force the select box to drop down using any code. But still you can change the selected option using the code. Pls see this

    http://www.mredkj.com/tutorials/tutorial003.html

    0 讨论(0)
  • 2020-11-29 09:28

    This should work:

    var element = $("select")[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.");
    }
    

    Example

    0 讨论(0)
  • 2020-11-29 09:28

    Just an update here as the accepted answer is correct but outdated and initMouseEvent is soon to be deprecated. [See: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/initMouseEvent]

    Use the following instead: new MouseEvent [See: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent]

    Example code:

    var el = $('select'); // grab the input (jQuery)
    var event = new MouseEvent('mousedown'); // create the event listener
    el.dispatchEvent(event); // attach the event listener to the element
    
    0 讨论(0)
提交回复
热议问题