Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Console log returning empty value when calling for input field variable

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading