0

I have the following code

<input type="text" id="text_box1" >

I need to set focus on this field programmatically.

What i tried from the console( after the page has loaded) doesn't seem to work.

1) $('#text_box1').focus();
2) document.getElementById("text_box1").focus();

Any idea on what is wrong here?

I am using jQuery 1.11.3

prajeesh
  • 1,610
  • 2
  • 24
  • 44

3 Answers3

3

It works! It must be called once after loading the DOM.

The below function will be called after the DOM are loaded

jQuery:

$(function(){
     //any other code which needs to be called after the DOM is completely loaded
});

Similary, with Javascript

window.onload = function() {
}

$(function(){

$('#text_box1').focus();

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="text_box1" >
Hary
  • 5,208
  • 6
  • 31
  • 67
0

just use autofocus attributein form field...

<input type="text" id="text_box1" autofocus />
0

Use the following JavaScript function, it will work.

<script type="text/javascript">
window.onload = function () 
{
document.getElementById("text_box1").focus();
};
</script>
Sahil Mahajan Mj
  • 12,525
  • 8
  • 53
  • 98
Sagar
  • 47
  • 1
  • 6
  • 1
    While this code may answer the question, it would be best if you could provide a little explanation for why it does so. – MTCoster Nov 16 '18 at 11:32
  • Window.Onload - Fires when the entire page loads, including its content (images, css, scripts, etc.) & document.onload - Fires when the DOM is ready which can be prior to images and other external content is loaded. – Sagar Nov 16 '18 at 12:11
  • 1
    You should edit your answer to include this explanation – MTCoster Nov 16 '18 at 12:12