Skip to content
Advertisement

Javascript insert value inside an input

I have to make a function in javascript that compiles this input with a value;

This is what i tried to do

document.getElementById("email").value = "testemail@gmail.com";

but i get this error:

TypeError: Cannot set property 'value' of null

html code:

    <div>
        <label class="block text-sm text-gray-800 mb-1 dark:text-gray-300" for="email">Email address</label>
        <input name="email" id="email" type="text" autocomplete="off" spellcheck="false" autocorrect="off" placeholder="lebron@gmail.com" value="">
        <div class="text-xs text-red-500 mt-1">Please enter your email address.</div>
    </div>

Advertisement

Answer

Call your JavaScript in this event listener. This will execute after the page has loaded therefore your email element should be on the page at this point.

window.addEventListener('load', function () {
    document.getElementById("email").value = "testemail@gmail.com";
})
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement