Javascript – How to set focus on an element in an HTML form using JavaScript

focushtmljavascripttextbox

I have a web form with a text box in it. How do I go about setting focus to the text box by default?

Something like this:

<body onload='setFocusToTextBox()'>

so can anybody help me with it? I don't know how to set focus to the text box with JavaScript.

<script>
  function setFocusToTextBox(){
    //What to do here
  }
</script>

Best Answer

Do this.

If your element is something like this..

<input type="text" id="mytext"/>

Your script would be

<script>
function setFocusToTextBox(){
    document.getElementById("mytext").focus();
}
</script>