Search code examples
javascripthtmlfocus

How to use javascript to focus (get the cursor on it) on an HTML <input type="text"> tag


Let's say there's I have the following code: -

    <div onclick="document.getElementById('inputfieldxyz').focus"> CLICK ME TO FOCUS ON THE INPUT TAG </div>

    <input id="inputfieldxyz" placeholder="This becomes ::focus 'ed when the div above is clicked">

So... Yeah... How do I click and the div and make the input tag show up the cursor like the way it does when the input tag is clicked?

P.S.: I can't use jQuery. Is there a way to do it using plain javascript? (Thanks in advance :)


Solution

  • With .focus() not .focus.

    <div onclick="document.getElementById('inputfieldxyz').focus()"> CLICK ME TO FOCUS ON THE INPUT TAG </div>
    
        <input id="inputfieldxyz" placeholder="This becomes ::focus 'ed when the div above is clicked">

    Alternatively, HTML5 also supprts the autofocus attribute :

    <input type="text" autofocus />