RoboPHP
RoboPHP

Reputation: 420

How to load value in input box on page load - JS

I am trying to set or load a value in my input box as quickly when the page is loading. With my code below, i notice the input box is empty for about a second or 2 seconds before the value is filled in the input box. IS there a way i can make the input box load along with the value ?

Loader.JS

   const myKey = document.querySelectorAll('.key__input');
document.onreadystatechange = function () {
    if (document.readyState === "complete") {
        myKey.forEach(function (key) {
            key.value = "Hello Stack OverFlow";
            key.focus();
        })

    }
}

Upvotes: 0

Views: 867

Answers (2)

codeandcloud
codeandcloud

Reputation: 55248

You should be writing the event on Window: DOMContentLoaded event (DOM Ready) not on Document: readystatechange event

 const keyInputs = document.querySelectorAll('.key__input');
 window.addEventListener('DOMContentLoaded', (event) => {
    keyInputs.forEach(function(keyInput) {
       keyInput.value = "Hello Stack OverFlow";
       keyInput.focus(); //focus will remain on the last selected element
     })
});

Upvotes: 1

gaetanoM
gaetanoM

Reputation: 42054

You need to wrap your code in the DOMContentLoaded:

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

window.addEventListener('DOMContentLoaded', function(e) {
    const myKey = document.querySelectorAll('.key__input');
    myKey.forEach(function (key) {
        key.value = "Hello Stack OverFlow";
        key.focus();
    })
})
<input type="text" class="key__input">

Upvotes: 1

Related Questions