6

I have multiple select boxes in the pages. I want to set focus on first element of specific select box. Here it shows how to set focus on select box. I need to say which one too. I tried below code but it didn't set the focus.

$('#thirdDropBox select:first').focus();
4
  • 1
    Why cant you just: $('#thirdDropBox').focus();? ID's are generally unique to an element. Dec 9, 2014 at 20:47
  • 1
    What does #thirdDropBox refer to? If it is the id for the select box then that is all you need in the selector (i.e. remove the select:first part).
    – ioums
    Dec 9, 2014 at 20:49
  • 1
    It would definitely help to see some of the HTML ...
    – rfornal
    Dec 9, 2014 at 20:50
  • can you put your code in a jsfiddle? Dec 9, 2014 at 20:50

2 Answers 2

10

If you want the user to have focus on the first of multiple select's, you can use the following jQuery code:

If you have an id for the first select, you can directly access that element with the following:

$(document).ready(function () {
    $('#idOfFirstSelect').focus();
}); 

However, if you don't have the id, the following code should work.

Demo: http://jsfiddle.net/biz79/1qo6mxnf/

$(document).ready(function () {
    $('select').first().focus();
});

On a separate note, if you also want to have a default option selected, you can set that option to "selected" in the HTML:

<option value="saab" selected="selected">Saab</option>
3
  • Great answer but if it literally is just the first "select" on the page with an ID. Then the above is overkill. Good answer though :) Dec 9, 2014 at 20:59
  • Thanks. Yes, if you have an id, you can directly specify that id in the selector. However, if you don't have the id, this should work.
    – Will
    Dec 9, 2014 at 21:01
  • I certainly agree. Worth mentioning in your answer? Dec 9, 2014 at 21:03
1

The JQuery selector:

$('#thirdDropBox select:first')

will select the first "select" html element that is a descendant of an html-element that has an ID-attribute with the value "thirdDropBox".

For more information see: http://api.jquery.com/descendant-selector/

You probably need to remove the '#thirdDropBox"-part from your selector:

$('select:first')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.