jQuery:如何在提交之前从表单中删除空白字段? [英] jquery: how to remove blank fields from a form before submitting?

查看:91
本文介绍了jQuery:如何在提交之前从表单中删除空白字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,上面有一组表单,用于API测试.由于不值得说明的原因,我通常不希望在向服务器提交的内容中包含空字段.提交前如何删除数据中的空白字段?

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?

例如,如果我有一个包含两个字段foo和bar的表单,并且用户将bar留空,那么我希望服务器将提交内容视为唯一的字段是foo.

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.

我的第一个刺入步骤涉及使用jquery与

My first stab at that involved looping through the fields using jquery with

$("form").submit(function() {
    $(this).children(':input').each(...)
}

并删除该字段.但是a)无效,b)似乎会从页面上的可见表单中删除该字段,这不是我想要的.

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.

另一种方法可能是遍历这些字段,并使用具有非"值的字段手动构造提交字符串.那行得通吗?还有更好的主意吗?

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?

推荐答案

一种方法是在这些字段上设置"disabled"属性,以防止其值被序列化并发送到服务器:

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");

已修复的错误

这篇关于jQuery:如何在提交之前从表单中删除空白字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆