Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
624 views
in Technique[技术] by (71.8m points)

jquery: how to remove blank fields from a form before submitting?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...