localhost
localhost

Reputation: 861

form value is empty

I am making a UI and below is my basic getting input from forms, but it won't display the value of secondLetter if I do it like

const form = document.querySelector('#form');
let firstLetter = document.querySelector('#firstLetter').value;
let secondLetter = document.querySelector('#secondLetter').value;
const output = document.querySelector('#check');

form.addEventListener('submit', function(e){
    e.preventDefault();
    console.log(secondLetter);
})

But If do it like

const form = document.querySelector('#form');
let firstLetter = document.querySelector('#firstLetter').value;
let secondLetter = document.querySelector('#secondLetter');
const output = document.querySelector('#check');

form.addEventListener('submit', function(e){
    e.preventDefault();
    console.log(form.secondLetter.value);
})

I get the value. I don't understand what I am doing wrong or why second example work and not first. Following is my HTML for reproducing purpose

    <form id="form">
    <label for="firstLetter">First Letter</label>
        <input type="text" id="firstLetter">
    <label for="secondLetter">Second Letter</label>
        <input type="text" id="secondLetter">
    <input type="submit" id="check">
</form>

Upvotes: 0

Views: 550

Answers (2)

Renaldo Balaj
Renaldo Balaj

Reputation: 2440

Your 1st code runs when the page loads (your form laod):

let secondLetter = document.querySelector('#secondLetter').value;

so secondLetter will be set to value "" , even when your form will be submited the varable is already set so you will get "".

AT the 2nd code: you set secondLetter to the element reference, and only on submit you give the value to secondLetter, not before the submit.

Upvotes: 2

Quentin
Quentin

Reputation: 943220

<input type="text" id="secondLetter"> doesn't have a value attribute, so document.querySelector('#secondLetter').value is going to be an empty string.

(If you wanted to type something into the input and then read the value, then your JS would need to wait until something had been typed … you would normally use an Event Listener for that).

Upvotes: 0

Related Questions