I'm using the Jquery Validation plugin to validate and submit my forms.
我正在使用Jquery Validation插件来验证和提交我的表单。
I want to be able to remove unnecessary form field values from the form data before they get posted to the server.
我希望能够在将表单数据发布到服务器之前从表单数据中删除不必要的表单字段值。
I figured that the submitHandler would be the best place for this - here is a sample of my code:
我认为submitHandler将是最好的地方 - 这是我的代码示例:
submitHandler: function(form) {
if (form.elements["billddress2"].value == "Suite/Apt"){
delete form.elements["billddress2"];
}
if (form.elements["mobile"].value == "Mobile Number"){
delete form.elements["mobile"];
}
if (form.elements["questionid_46"].value == "Guest Email"){
delete form.elements["questionid_46"];
}
form.submit();
}
The problem is that the data still gets passed. I know that I have the right properties, since i tested them using form.elements["name"].value.
问题是数据仍然通过。我知道我有正确的属性,因为我使用form.elements [“name”]。值来测试它们。
Anyone know why I can't delete HTMLFormElement Object properties?
任何人都知道为什么我不能删除HTMLFormElement对象属性?
1 个解决方案
#1
2
The problem is that delete
is meant to remove properties from objects, whereas you're trying to remove elements from the DOM. In your callback function, form
is a DOM element, so you can't remove its children with delete. You could try using remove
on the form elements (you'll have to turn them into jQuery objects with $
first), like this:
问题是删除意味着从对象中删除属性,而您尝试从DOM中删除元素。在回调函数中,form是一个DOM元素,因此您无法通过delete删除其子元素。您可以尝试在表单元素上使用remove(您必须使用$ first将它们转换为jQuery对象),如下所示:
submitHandler: function(form) {
var form = $(form);
if (form.elements["billddress2"].value == "Suite/Apt"){
$('input[name="billddress2"]', form).remove();
}
if (form.elements["mobile"].value == "Mobile Number"){
$('input[name="mobile"]', form).remove();
}
if (form.elements["questionid_46"].value == "Guest Email"){
$('input[name="questionid_46"]', form).remove();
}
form.submit();
}
#1
2
The problem is that delete
is meant to remove properties from objects, whereas you're trying to remove elements from the DOM. In your callback function, form
is a DOM element, so you can't remove its children with delete. You could try using remove
on the form elements (you'll have to turn them into jQuery objects with $
first), like this:
问题是删除意味着从对象中删除属性,而您尝试从DOM中删除元素。在回调函数中,form是一个DOM元素,因此您无法通过delete删除其子元素。您可以尝试在表单元素上使用remove(您必须使用$ first将它们转换为jQuery对象),如下所示:
submitHandler: function(form) {
var form = $(form);
if (form.elements["billddress2"].value == "Suite/Apt"){
$('input[name="billddress2"]', form).remove();
}
if (form.elements["mobile"].value == "Mobile Number"){
$('input[name="mobile"]', form).remove();
}
if (form.elements["questionid_46"].value == "Guest Email"){
$('input[name="questionid_46"]', form).remove();
}
form.submit();
}