jquery:如何在提交之前从表单中删除空白字段?

发布于 2024-11-06 00:37:25 字数 409 浏览 0 评论 0原文

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

例如,如果我有一个包含两个字段(foo 和 bar)的表单,并且用户将 bar 留空,我希望服务器看到提交,就好像唯一的字段是 foo 一样。

我的第一次尝试涉及使用 jquery 循环遍历字段

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

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

另一种方法可能是循环遍历字段并使用具有除“”之外的值的字段手动构造提交字符串。那行得通吗?还有更好的想法吗?

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?

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.

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

$("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.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

檐上三寸雪 2024-11-13 00:37:25

一种方法是在这些字段上设置“禁用”属性,这会阻止它们的值被序列化并发送到服务器:

$(function()
{
    $("form").submit(function()
    {
        $(this).children(':input[value=""]').attr("disabled", "disabled");

        return true; // ensure form still submits
    });
});

如果您有客户端验证,您还需要在事件中重新启用这些字段验证失败:

$(':input').removeAttr("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");

EDIT: repaired bug

两个我 2024-11-13 00:37:25

将此处的答案与有关查找空输入的问题结合起来我得出了这个解决方案。

$(function() {
   $("form").submit(function() {
      $(this).find(":input").filter(function(){ return !this.value; }).attr("disabled", "disabled");
      return true; // ensure form still submits
    });
});

因此,从 @Luke 的解决方案开始,添加他使用 find 而不是 child 的建议(我的表单位于表格中),然后使用 @gdoron 的过滤技术来隔离空元素。

Combining the answers here, with this question regarding finding empty input I 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.

幻梦 2024-11-13 00:37:25

我通常会同意@Luke,但下面的解决方案应该处理任何空值,无论它是否是输入标签,只要记住在所有表单子元素上添加名称属性(如果您希望它们被序列化) ;

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>    

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

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;

The 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:

$("#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
    });
});
归属感 2024-11-13 00:37:25

投票最高的答案对我不起作用。我认为选择器不够具体。这对我有用:

$(function() {
  $("#myForm").submit(function() {
    $("#myForm *").filter(":input").each(function(){
      if ($(this).val() == '')
        $(this).prop("disabled", true);
    });

    return true; // ensure form still submits
  });
});

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

胡渣熟男 2024-11-13 00:37:25

删除提交时的空字段

$(function() {
    $('form').submit(function () {
        var $empty_fields = $(this).find(':input').filter(function () { 
            return $(this).val() === '';
        });
        $empty_fields.prop('disabled', true);
        return true;
    });
});

结合多个功能和主观样式,特别是:

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:

  • .find() goes deeper than .children().
  • .val() === '' works for textarea and changed attributes, [value=""] does not.
  • .prop() over .attr().
赤濁 2024-11-13 00:37:25

添加卢克·丹尼斯接受的答案。如果有人使用 Python/Django 框架,如果您使用 django-filters 应用程序,此脚本可能会有所帮助。在此示例中,我有多个具有输入和选择器 html 元素的过滤器。但是,该脚本也适用于单输入过滤器和多选过滤器。

$(function()
{
    var form = $( 'form' )[0];
    $( form ).submit(function() 
    { 
        $('input, select').each(function()
        {
            if ($(this).val().length === 0) 
            {
                $(this).prop('disabled', true);
                $(this).next().prop('disabled', true);
            }
        });
    });
});

Adding to Luke Dennis accepted answer. In case someone uses the Python/Django framework this script might help if you use the django-filters app. In this example I had multiple filters that had an input and selector html element. However, the script also worked on single input filters as well as multiplechoice filters.

$(function()
{
    var form = $( 'form' )[0];
    $( form ).submit(function() 
    { 
        $('input, select').each(function()
        {
            if ($(this).val().length === 0) 
            {
                $(this).prop('disabled', true);
                $(this).next().prop('disabled', true);
            }
        });
    });
});
眼泪都笑了 2024-11-13 00:37:25

也许不是最好的解决方案,但这应该是实现您想要的目标的快速而简单的方法然后

$("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');

    });
}

,如果您使用 vlient 端验证或通过 ajax 发布,那么您需要将 name 属性设置回来,以便下一次提交可以工作正确地...

$(this).attr('name', $(this).attr('blank'));
$(this).removeAttr('blank');

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...

$(this).attr('name', $(this).attr('blank'));
$(this).removeAttr('blank');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文