how to perform setfocus(); to the dropdown list

madhu picture madhu · Nov 5, 2012 · Viewed 13k times · Source

I'm having a dropdown list which loads the records from DB on OnLoad() event, I want to set focus on the dropdown box when the page loads. I have tried many ways to set focus but its not working. pls look at the code below.

HTML CODE is as follows,

 <body onLoad="getDataSourceList()">
<div class="wrapper">   


    <form id="myUploadForm" name="myUploadForm">

    <table width="100%">
            <tr> <td align="right"><label for="dataSourceId" style=" font-family: serif; font-size: small;">DataSource Type<b style="color: red">*</b>: </label> </td> 
                 <td><select name="dataSourceType" id="dataSourceId">
                        <option value="Select"> Select</option>
                    </select>
                 </td> 
            </tr>

        </table>

    </form>


My ajax code goes below :

function getDataSourceList() {
    $.ajax({
        url : '/DataWeb/getAllDataSources',
        type : 'post',
        dataType : 'json',
        contentType : 'application/json',

        success : function(map) {
            console.log(map);
            var select = document.getElementById("dataSourceId");
            for (index in map) {
                select.options[select.options.length] = new Option(
                        map[index], index);
            }
        },

        error : function(map) {
            console.log(map);
            console.log("error occured!!!");
        },

    });
    document.getElementById('dataSourceId').focus();
}

Thanks in advance.

Answer

arrest warrant picture arrest warrant · Nov 5, 2012
$(document).ready(function(){
 $("#myid").focus();
});

This works for me...