Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set focus on specific select box

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();
like image 817
αƞjiβ Avatar asked Dec 25 '22 01:12

αƞjiβ


2 Answers

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>
like image 177
Will Avatar answered Jan 09 '23 03:01

Will


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')
like image 43
PvdBlankevoort Avatar answered Jan 09 '23 01:01

PvdBlankevoort