Search code examples
javascriptselectauto

I want to make the modal input filed automatically selected when the modal is appear so i can type in it directly without put the cursor in the filed


what I can't figure it out is how to make the add.onclick also make the input field auto-selected so that is I directly access it using the keyboard without move the cursor to the input filed

const add = document.querySelector("#add");
const overlay = document.querySelector(".overlay");
const input = document.querySelector(".modal .body input");

add.onclick = () => { 
    document.querySelector(add.dataset.target).classList.add("active");
    overlay.classList.add("activeLay");
    //?????
};


        <body>
            <div class="overlay"></div>
            <div class="modal" id= "inputData">
                <div class="header">
                    <h2>Add Task</h2>
                    <button class= "close">&times</button>
                </div>
                <div class="body">
                     <input type="text">
                     <button type="submit" id= "plus">Add Task</button>
                </div>
            </div>
            <div class="continer">
                <div class="todo task" id= "Taskes">
                    <h2>Tasks</h2>
                    <button type= "submit" id= "add" data-target= "#inputData">+ Add Task</button>
                </div>
           </div>
        </body>

Solution

  • element.focus() set element get selected without click or tab. Reference here

    After clicking add button, javascript sets focus on input tag by element.focus().

    const add = document.querySelector("#add");
    const overlay = document.querySelector(".overlay");
    const input = document.querySelector(".modal .body input");
    
    add.onclick = () => { 
        document.querySelector(add.dataset.target).classList.add("active");
        overlay.classList.add("activeLay");
        input.focus();
    };
    <body>
                <div class="overlay"></div>
                <div class="modal" id= "inputData">
                    <div class="header">
                        <h2>Add Task</h2>
                        <button class= "close">&times</button>
                    </div>
                    <div class="body">
                         <input type="text">
                         <button type="submit" id= "plus">Add Task</button>
                    </div>
                </div>
                <div class="continer">
                    <div class="todo task" id= "Taskes">
                        <h2>Tasks</h2>
                        <button type= "submit" id= "add" data-target= "#inputData">+ Add Task</button>
                    </div>
               </div>
            </body>