20

I currently have a textbox in my aspx:

 <input type="text" id="myTextbox"  value="" />

I was wondering if I could set the focus (put my cursor in that text box) every time my JavaScript method is called. I was hoping it would work along the lines of this:

function setFocus() {
    document.getElementById("myTextbox").Focus();
}

Any suggestions?

unor
  • 92,415
  • 26
  • 211
  • 360
user1219627
  • 767
  • 6
  • 11
  • 17

2 Answers2

30

Invoke the lowercase .focus() function:

function setFocus() {
    document.getElementById("myTextbox").focus();
}
  • 2
    Thanks, All the examples showed uppercase so i just assumed when it didnt work that i was just implementing it wrong. I'll mark you as the answer once it allows me to. Thanks! – user1219627 Mar 03 '12 at 06:18
  • 1
    Note that this won't work if you're trying it out in the console. For Chrome at least. – Shivanshu Goyal Oct 16 '16 at 19:20
4

Try this:

function setFocus(id) {
    document.getElementById(id).focus();

}

In this way, your function becomes reusable. Just pass the ID of the html element to be given the focus when you call the function.

M.

Marco Grazia
  • 57
  • 1
  • 4