23

I use this code for simulate click on select element:

$(function(){
   $("#click").click(function(){
       $("#ts").click();
       //$("#ts").trigger("click");
   });
});

and HTML code is:

<select id="ts">
    <option value="1">1</option>
    <option value="2">Lorem ipsum dolor s.</option>
    <option value="3">3</option>
</select>

<input type="button" id="click" value="Click"/>

I test click and trigger but both not work.

Thanks for any help.

Morteza
  • 2,143
  • 7
  • 37
  • 61

6 Answers6

35

Well, you cannot attach click event to html select but you can do this tricky thing...

Take a look at here:

Live DEMO:

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

Oscar Jara
  • 14,129
  • 10
  • 62
  • 94
  • Have'nt seen that one before, works for me, but something tells me it's not cross browser. +1 anyway. – adeneo Nov 05 '12 at 15:32
  • It's working perfect in `chrome` let me see if I can do better for other browsers :-) – Oscar Jara Nov 05 '12 at 15:32
  • I'm guessing you'll need createEventObject for some browsers, but it will still probably have issues, and I don't think there's a way to do this that will work everywhere, at least I have'nt seen the createEvent method used much. – adeneo Nov 05 '12 at 15:40
  • 2
    works for me. this is great! however it doesn't work on IE 7. – Eytch Feb 25 '14 at 13:16
  • initMouseEvent() is depricated. https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/initMouseEvent – Scott Sword May 08 '15 at 17:59
  • the Mozilla Developer network says the method MouseEvents.initMouseEvent() is deprecated [link](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/initMouseEvent) Any other solution ? – Parth Kapadia Feb 18 '16 at 12:10
  • 3
    IE 9, doesn't work, IE 10 Doesn't work, IE 11 Doesn't work, FF most recent, doesn't work. do we have an alternative? – Jean-Paul Aug 03 '16 at 08:47
18

This is the best cross browser method i think you can get. Tested on Safari, Firefox, Chrome and IE. For Chrome, Oscar Jara's answer is the way to go. (update: 10-13-2016)

$(function() {
    $("#click").on('click', function() {
        var $target = $("#ts");
        var $clone = $target.clone().removeAttr('id');
        $clone.val($target.val()).css({
            overflow: "auto",
            position: 'absolute',
            'z-index': 999,
            left: $target.offset().left,
            top: $target.offset().top + $target.outerHeight(),
            width: $target.outerWidth()
        }).attr('size', $clone.find('option').length > 10 ? 10 : $clone.find('option').length).change(function() {
            $target.val($clone.val());
        }).on('click blur keypress',function(e) {
         if(e.type !== "keypress" || e.which === 13)
            $(this).remove();
        });
        $('body').append($clone);
        $clone.focus();
    });
});

See jsFiddle demo

A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • I used this code tonight but had a few difficulties: the left and top lines both had to be offset for margins (using box-sizing:border-box if it matters). The harder part was that I had set my select css to height:20px, which the regular select properly overrides for the drop down. With this code it did not override. Switching my css to min-height:20px was sufficient for my problem. An hour of hair-pulling deserved to be shared :-) – Stephen Jan 03 '16 at 03:52
  • it doesn't understand hiting enter in FF. – Fanky Jan 10 '17 at 16:38
  • 1
    @Fanky Updated code and jsFiddle. Did it what you mean? – A. Wolff Jan 10 '17 at 18:01
4

This is as close as you'll get I think :

$(function(){
   $("#click").on('click', function(){
       var s = $("#ts").attr('size')==1?5:1
       $("#ts").attr('size', s);
   });
   $("#ts option").on({
       click: function() {
           $("#ts").attr('size', 1);
       },
       mouseenter: function() {
           $(this).css({background: '#498BFC', color: '#fff'});
       },
       mouseleave: function() {
           $(this).css({background: '#fff', color: '#000'});
       }
   });
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
2

I ended up setting the selected attribute on the option itself. Then triggering the change even on the select element.

Paul Wand
  • 323
  • 5
  • 12
0

I have a complex select element, fed by the answer given in a previous select element. Options are fed by AJAX, triggered by onchange events.

For my needs, to prefill answers with a "hidden magic event" that simulates user behavior (in an intensive testing way) I use the following jQuery code in "my magic event". It selects the option by its index :

// Quick feed of my Car Form    
document.getElementById('carbrand').selectedIndex = 30; // "PORSCHE"
document.getElementById('carbrand').onchange();

var timeoutID = window.setTimeout(function () {

    document.getElementById('model').selectedIndex = 1; // "911"
    document.getElementById('model').onchange();

    var timeoutID = window.setTimeout(function () {
        document.getElementById('energy').selectedIndex = 1; // "SUPER"
        document.getElementById('energy').onchange();
    } , 200);

} , 200);

Merci à https://stackoverflow.com/users/1324/paul-roub pour les corrections ;-)

Community
  • 1
  • 1
Vivien G.
  • 79
  • 4
-3

little update(with toggle) for Oscar Jara variant
http://jsfiddle.net/mike_s/y5GhB/

  • 4
    Note that [link-only answers](http://meta.stackoverflow.com/tags/link-only-answers/info) are discouraged, SO answers should be the end-point of a search for a solution (vs. yet another stopover of references, which tend to get stale over time). Please consider adding a stand-alone synopsis here, keeping the link as a reference. – kleopatra Oct 14 '13 at 13:12