3

A quick question. Can i simulate click on a select box (irrespective of the id or class of the selectbox) inside a div using JQuery. There is only one select box in the div. Thanks in advance

Here is the HTML:

<div class="custom-select">
<select id="operator_select">
<option  value="1">1</option>
<option  value="2">2</option>
<select>
</div>

Jquery code that I tried:

    $(function(){
     $(".custom-select").click(function(){
       $('select',this).click();
       });
     });

here's a fiddle: http://jsfiddle.net/arjdev/5Sch2/

Tasos K.
  • 7,979
  • 7
  • 39
  • 63
ArJ
  • 395
  • 5
  • 14
  • Are you trying to programatically open the drop-down menu? http://stackoverflow.com/questions/13234971/simulate-click-on-select-element-with-jquery – George Feb 21 '14 at 12:17
  • yes, i am tring that. @oGeez – ArJ Feb 21 '14 at 12:46

3 Answers3

2
$(function () {
    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");
        }
    }

    $(".custom-select").click(function () {
        open($(this).find('select'));
    });
});

Your select tag is also not ended </select>.

Fiddle

Tomanow
  • 7,247
  • 3
  • 24
  • 52
  • have you tried it? it didnt work for me. can you provide a fiddle? – ArJ Feb 21 '14 at 12:42
  • Thanks, nice work.. I didn't think of going that far (creating a custom event). – ArJ Feb 24 '14 at 08:07
  • Just a note, for me changing function name from `open` to something else `openSim` worked. Because open was opening new browser tab. – onetwo12 Oct 29 '14 at 08:52
0

try trigger method

 $(function(){
 $(".custom-select").click(function(){
   $('select').trigger( "click" );
   });
 });
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
0

try this.. it will trigger on form load

    $(document).ready(function() {
         $('.custom-select').find('select').trigger('click');
    });
chriz
  • 1,339
  • 2
  • 16
  • 32