1

I have a drop down say

<select id="countries">
<option value="1">Country</option>
</select>

and a check box,

<input type="checkbox" name="search_engine" id="search_engine" class="hear" value="search_engine" />
<input type="checkbox" name="search_engine1" id="search_engine1" class="hear" value="search_engine1" />
<input type="checkbox" name="search_engine2" id="search_engine2" class="hear" value="search_engine2" />

On the click of the checkbox I want to open the drop down, how can I do that using jquery.

Tried the below code but its not working, I am using jquery 1.10.3

function open_drop_down()
{
   $('#countries').show().focus().click();
}
  • 2
    An ID can only be used once per page. [IDs must be unique.](http://www.w3.org/TR/html5/dom.html#the-id-attribute) – rink.attendant.6 Aug 09 '13 at 06:17
  • ok I shall update my code but I have tried focus it does not work either. –  Aug 09 '13 at 06:20
  • Updated the question now I have my id's different but the point is that `focus()` does not work! –  Aug 09 '13 at 06:22
  • @rink.attendant.6 no it doesnot work check my jsfiddle http://jsfiddle.net/fakhruddin/bXv9N/ –  Aug 09 '13 at 06:36
  • @rink.attendant.6 as i said it just sets focus but doesnot open the dropdown –  Aug 09 '13 at 06:37
  • Same questions? http://stackoverflow.com/questions/249192/how-can-you-programmatically-tell-an-html-select-to-drop-down-for-example-due – andyf Aug 09 '13 at 07:13

1 Answers1

2

EDIT: From mithunsatheesh's answer, I have integrated the doClick function here:

var doClick = function() {
    'use strict';
    var event = document.createEvent('MouseEvents');
    event.initMouseEvent('mousedown', true, true, window);
    return event;
};

$('.hear').click(function() {
    'use strict';
    $('#countries').focus().get(0).dispatchEvent(doClick());
});

See jsFiddle. Please note that it only works in Chrome (WebKit).

Also, you may wish to bind to the change event.

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
  • I am using class instead of ID but still `focus();` does not work. It just sets the focus and not expand the dropdown. –  Aug 09 '13 at 06:18
  • getting an error `Cannot call method 'dispatchEvent' of undefined ` –  Aug 09 '13 at 06:55