[英]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.为什么在调用文本输入的变量时 console.log 返回一个空行。
HTML HTML
<label for="subject">Subject</label>
<input type="text" id="subject" name="ticket-subject" />
Javascript Javascript
I tried the actual form and its console.log
worked perfectly on submit, but somehow the value for ticketSubject
seems to be empty.我尝试了实际的表单,它的
console.log
在提交时工作得很好,但不知何故ticketSubject
的值似乎是空的。
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:改为读取
submit
事件处理程序中的值:
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()
您需要读取
addEventListener()
处理程序中的值,否则该值会在事件发生之前存储,并且永远不会显示在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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.