Home > Enterprise >  Console log returning empty value when calling for input field variable
Console log returning empty value when calling for input field variable

Time:03-22

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:

CodePudding user response:

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 >
  <label for="subject">Subject</label>
  <input type="text" id="subject" name="ticket-subject" />
  <input type="submit" value="Submit" />
</form>

CodePudding user response:

You need to read the value inside the addEventListener() handler, otherwise the value is stored before the event and will never show up on the console.log()

const ticketForm = document.querySelector('.ticket-form')


ticketForm.addEventListener('submit', e => {
  e.preventDefault()
  console.log(document.getElementById('subject').value);
  console.log('The form submit works')
})
<form >
  <label for="subject">Subject</label>
  <input type="text" id="subject" name="ticket-subject" />
  <button type="submit"> submit</button>
</form>

  • Related