通过 JavaScript Class 处理时,序列化时表单字段为空
Form fields are empty on serialize when processed thru JavaScript Class
我希望我的问题在某种程度上是可以理解的,我有一个 ES6 Class,它在常规表单上初始化,然后通过 ajax 调用(未包含在示例中)进行处理。
当我尝试序列化 formData 时,它 return 是空的,而不是 first_name 输入的值。添加或删除 类 等表单上的其他操作工作正常,只是表单不会 return 任何数据。我假设我不知何故失去了我的 $.this 范围。我刚开始尝试在模块和 Class 中构建我的 JavaScript 和抽象编码。当我使用常规 jQuery 就绪代码调用和处理表单时,该表单按预期工作,但就是无法弄清楚问题出在哪里。
script.js
import $ from 'jquery'
class CustomSubmit extends window.HTMLElement {
constructor (...args) {
const self = super(...args)
self.init()
return self
}
init () {
this.$ = $(this)
this.resolveElements()
this.bindFunctions()
this.bindEvents()
}
resolveElements () {
// Get the Form
this.$bidForm = $( '#CustomSubmitForm' , this)
}
bindFunctions () {
this.sendForm = this.sendForm.bind(this)
}
bindEvents () {
// Attach sendForm function to Form Submit
this.$.submit('[data-form-submit]', this.sendForm)
}
sendForm (e) {
e.preventDefault()
const formData = this.$.serialize()
// here is the problem, formData is empty
console.log(formData)
}
}
window.customElements.define('submit-form', CustomSubmit, { extends: 'form' })
form.html
<form is="submit-form" id="CustomSubmitForm">
<input type="text" name="first_name" id="first_name">
<button type="submit" [data-form-submit] >Submit Form</button>
</form>
问题似乎是您正在使用
class CustomSubmit extends window.HTMLElement {
但是普通的 HTMLElement
没有 any <form>
-specific properties and methods 允许 jQuery 从所有元素收集值。相反,使用
class CustomSubmit extends window.HTMLFormElement {
// ^^^^
我希望我的问题在某种程度上是可以理解的,我有一个 ES6 Class,它在常规表单上初始化,然后通过 ajax 调用(未包含在示例中)进行处理。
当我尝试序列化 formData 时,它 return 是空的,而不是 first_name 输入的值。添加或删除 类 等表单上的其他操作工作正常,只是表单不会 return 任何数据。我假设我不知何故失去了我的 $.this 范围。我刚开始尝试在模块和 Class 中构建我的 JavaScript 和抽象编码。当我使用常规 jQuery 就绪代码调用和处理表单时,该表单按预期工作,但就是无法弄清楚问题出在哪里。
script.js
import $ from 'jquery'
class CustomSubmit extends window.HTMLElement {
constructor (...args) {
const self = super(...args)
self.init()
return self
}
init () {
this.$ = $(this)
this.resolveElements()
this.bindFunctions()
this.bindEvents()
}
resolveElements () {
// Get the Form
this.$bidForm = $( '#CustomSubmitForm' , this)
}
bindFunctions () {
this.sendForm = this.sendForm.bind(this)
}
bindEvents () {
// Attach sendForm function to Form Submit
this.$.submit('[data-form-submit]', this.sendForm)
}
sendForm (e) {
e.preventDefault()
const formData = this.$.serialize()
// here is the problem, formData is empty
console.log(formData)
}
}
window.customElements.define('submit-form', CustomSubmit, { extends: 'form' })
form.html
<form is="submit-form" id="CustomSubmitForm">
<input type="text" name="first_name" id="first_name">
<button type="submit" [data-form-submit] >Submit Form</button>
</form>
问题似乎是您正在使用
class CustomSubmit extends window.HTMLElement {
但是普通的 HTMLElement
没有 any <form>
-specific properties and methods 允许 jQuery 从所有元素收集值。相反,使用
class CustomSubmit extends window.HTMLFormElement {
// ^^^^