jquery:如何在提交前从表单中删除空白字段?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5904437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery: how to remove blank fields from a form before submitting?
提问by Dave Orr
I have a page with a set of forms on it, used for API testing. For reasons not worth explicating, I generally don't want to include empty fields in the submission to the server. How do I delete empty fields from the data before submitting?
我有一个页面,上面有一组表单,用于 API 测试。出于不值得解释的原因,我通常不想在提交给服务器的文件中包含空字段。如何在提交前从数据中删除空字段?
For example, if I have a form with two fields, foo and bar, and the user leaves bar blank, I want the server to see the submission as if the only field were foo.
例如,如果我有一个包含两个字段 foo 和 bar 的表单,并且用户将 bar 留空,我希望服务器看到提交,就好像唯一的字段是 foo。
My first stab at that involved looping through the fields using jquery with
我的第一次尝试涉及使用 jquery 循环遍历字段
$("form").submit(function() {
$(this).children(':input').each(...)
}
And removing the field. But that a) didn't work, and b) seems like it would delete the field from the visible form on the page which is not what I want.
并删除该字段。但是a)不起作用,b)似乎会从页面上的可见表单中删除该字段,这不是我想要的。
Another approach might be to loop through the fields and construct the submit string manually with fields that have values other than "". Will that work? Any better ideas?
另一种方法可能是遍历字段并使用具有除“”以外的值的字段手动构建提交字符串。那行得通吗?有什么更好的想法吗?
回答by Luke Dennis
One way would be to set the "disabled" attribute on those fields, which prevents their values from being serialized and sent to the server:
一种方法是在这些字段上设置“禁用”属性,以防止它们的值被序列化并发送到服务器:
$(function()
{
$("form").submit(function()
{
$(this).children(':input[value=""]').attr("disabled", "disabled");
return true; // ensure form still submits
});
});
If you have client-side validation, you'll also want to re-enable these fields in the event of a validation failure:
如果您有客户端验证,您还需要在验证失败时重新启用这些字段:
$(':input').removeAttr("disabled");
EDIT: repaired bug
编辑:修复了错误
回答by ReggieB
Combining the answers here, with this question regarding finding empty inputI arrived at this solution.
结合此处的答案,以及有关查找空输入的问题,我得出了此解决方案。
$(function() {
$("form").submit(function() {
$(this).find(":input").filter(function(){ return !this.value; }).attr("disabled", "disabled");
return true; // ensure form still submits
});
});
So starts form @Luke's solution, adds his suggestion of using find instead of children (my form is in a table), and then uses @gdoron's filter technique to isolate the empty elements.
所以从@Luke 的解决方案开始,添加他使用 find 而不是 children 的建议(我的表单在表格中),然后使用 @gdoron 的过滤技术来隔离空元素。
回答by Ady Ngom
I generally will just agree with @Luke, but the solution below should take care of any empty value regardless if it is an input tag or not, just remember to add a name property on all your form children elements if you want them to get serialized;
我通常只会同意@Luke,但下面的解决方案应该处理任何空值,无论它是否是输入标签,只要记住在所有表单子元素上添加 name 属性,如果您希望它们被序列化;
The HTML:
HTML:
<form action="yourUrl.php" name="myForm" id="myForm">
input1: <input type="text" name="field1" /><br /><br />
input2: <input type="text" name="field2" /><br /><br />
input3: <input type="text" name="field3" /><br /><br />
input4: <input type="text" name="field4" /><br /><br />
select: <select name="selectField">
<option value="">empty value</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
</select><br /><br />
<input type="submit" name="submit" value="submit" />
</form>
The jQuery:
jQuery:
$("#myForm").submit (function (e) {
e.preventDefault();
var _form = $(this);
var data = {};
var formData = _form.serializeArray();
$.each(formData, function (index, value) {
var data_name = formData[index].name;
var data_value = formData[index].value;
if (data_value !== "") {
data[data_name] = data_value;
}
});
// now with ajax you can send the sanitize data object
$.post(_form.attr("action"), data, function(res, textStatus, jqXHR) {
// do something
});
});
回答by Ken Brockert
The top voted answer did not work for me. I believe the selectors weren't specific enough. Here's what worked for me:
最高投票的答案对我不起作用。我相信选择器不够具体。以下是对我有用的内容:
$(function() {
$("#myForm").submit(function() {
$("#myForm *").filter(":input").each(function(){
if ($(this).val() == '')
$(this).prop("disabled", true);
});
return true; // ensure form still submits
});
});
回答by Bob Stein
Removing empty fields on submit
提交时删除空字段
$(function() {
$('form').submit(function () {
var $empty_fields = $(this).find(':input').filter(function () {
return $(this).val() === '';
});
$empty_fields.prop('disabled', true);
return true;
});
});
Combining several features and subjective styles, especially:
结合几个特点和主观风格,尤其是:
回答by Dean North
Maybe not the best solution but this should be a quick and easy way to achieve what you're after
也许不是最好的解决方案,但这应该是实现您所追求的快速简便的方法
$("form").submit(function() {
$(this).children('input[value=""]').each(function(){
// Rename the name attribute to something else if the value is "" to it isn't submitted
$(this).attr('blank', $(this).attr('name'));
$(this).removeAttr('name');
});
}
Then if you are using vlient side validation or are posting via ajax, then you need to set the name attribute back so the next submission will work correctly...
然后,如果您使用 vlient 端验证或通过 ajax 发布,那么您需要重新设置 name 属性,以便下一次提交可以正常工作...
$(this).attr('name', $(this).attr('blank'));
$(this).removeAttr('blank');