Why is console.log returning an empty line when calling for a text input’s variable.
HTML
<label for="subject">Subject</label>
<input type="text" id="subject" name="ticket-subject" />
Javascript
I tried the actual form and its console.log worked perfectly on submit, but somehow the value for ticketSubject seems to be empty.
const ticketForm = document.querySelector('.ticket-form')
const ticketSubject = document.getElementById('subject').value;
ticketForm.addEventListener('submit', (e)=> {
e.preventDefault()
console.log(ticketSubject)
console.log('The form submit works')
})
Here’s the subject field:

But it returns nothing:

Advertisement
Answer
You’re reading the value of the input immediately when the page first loads, before the user has had a chance to enter a value. Read the value in the submit event handler instead:
const ticketForm = document.querySelector('.ticket-form')
ticketForm.addEventListener('submit', (e)=> {
e.preventDefault()
// read the value here
const ticketSubject = document.getElementById('subject').value;
console.log(ticketSubject)
console.log('The form submit works')
})<form class="ticket-form"> <label for="subject">Subject</label> <input type="text" id="subject" name="ticket-subject" /> <input type="submit" value="Submit" /> </form>