简体   繁体   中英

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

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:

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM