sam No1 sam No1 - 7 months ago 13
Javascript Question

How to focus on an element using jQuery?

I have following html

<div>
<span>Click me</span>
<select>
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>


jQuery:

$('span').on('click', function () {
$('select').focus();
});


What I want to do is when I click on span tag the select menu needed to be focused and dropped down without changing the structure. I spent hours to find a solution for this but I couldn't.

http://jsfiddle.net/dqc9nLgk/1/

Answer

You have used input as selector in fiddle. it should be select instead:

$('span').on('click', function () {
  $('select').focus(); 
});

Working Demo

Update: For opening dropdown-

var dropdown = $('select')[0];
event = document.createEvent('MouseEvents');
event.initMouseEvent('mousedown', true, true, window);
dropdown.dispatchEvent(event);

Working Demo