3

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.

madhu
  • 1,010
  • 5
  • 20
  • 38
  • You might try to put `document.getElementById('dataSourceId').focus();` statement to `success` callback, just after `for` loop. – Dfr Nov 05 '12 at 06:47
  • Your example seem working ok: http://jsfiddle.net/7phq8/ I guess problem could be with javascript loading order or elsewhere. – Dfr Nov 05 '12 at 07:35

2 Answers2

2
$(document).ready(function(){
 $("#myid").focus();
});

This works for me...

arrest warrant
  • 344
  • 2
  • 17
1

Try adding a tab index to dataSourceId element. refer to Which HTML elements can receive focus? for details on the elements on which focus() applies.

Community
  • 1
  • 1