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












26















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?










share|improve this question



























    26















    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?










    share|improve this question

























      26












      26








      26


      13






      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?










      share|improve this question














      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?







      jquery form-submit






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked May 5 '11 at 21:43









      Dave OrrDave Orr

      8671818




      8671818
























          6 Answers
          6






          active

          oldest

          votes


















          38














          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






          share|improve this answer


























          • That is really elegant... only it doesn't seem to work. What am I missing? In particular, on submission via http get so I can see what's going on, I still see something like 'api/userattributes/?action=read_by_user&name=&value=' where name and value were left blank, but still show up as submitting variables.

            – Dave Orr
            May 5 '11 at 22:29













          • On further investigation, ':input[value=""]' isn't finding anything. Walking through with a debugger after I split out the attr() call onto another line via each() shows that it never gets there, so disabled is never getting set.

            – Dave Orr
            May 5 '11 at 22:59






          • 1





            @Dave: I suspect that if you change $(this).children to $(this).find, it'll work in either place.

            – Luke Dennis
            May 6 '11 at 20:26






          • 1





            @FelipeTadeo: It should, because it's not using the "input" selector, but rather ":input", which is a jQuery-specific way to target inputs, textareas, selects, etc. However, the [value=""] part of the selector may not work with textarea. Best way might be to use a filtering function, similar to this: .children(':input').filter(function(item){ return !!$(item).val(); /* untested */ })

            – Luke Dennis
            Jan 16 '13 at 0:00








          • 2





            Recent versions of jQuery include the prop method. They recommend using that method rather than the attr method to set the disabled attribute so @LukeDennis code should be updated to $(this).children(':input[value=""]').prop('disabled', true);

            – jdp
            Jan 6 '15 at 15:30



















          17














          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.






          share|improve this answer


























          • No - I think they are a figment of an over-imaginative mind.

            – ReggieB
            Sep 28 '17 at 7:23











          • This should be the accepted answer. The accepted answer basically checks the input value when initially rendered (which may change), this answer checks the live input value when submitted.

            – Hudri
            Nov 12 '18 at 13:49





















          5














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





          share|improve this answer

































            1














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








            share|improve this answer
























            • also for me two i think the selector not working

              – Baha'a Odeh
              Aug 13 '18 at 21:10



















            0














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





            share|improve this answer
























            • @Luke just beat me to it with an almost identical answer, I prefer Luke's solution. :)

              – Dean North
              May 5 '11 at 21:55



















            0














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






            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f5904437%2fjquery-how-to-remove-blank-fields-from-a-form-before-submitting%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              6 Answers
              6






              active

              oldest

              votes








              6 Answers
              6






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              38














              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






              share|improve this answer


























              • That is really elegant... only it doesn't seem to work. What am I missing? In particular, on submission via http get so I can see what's going on, I still see something like 'api/userattributes/?action=read_by_user&name=&value=' where name and value were left blank, but still show up as submitting variables.

                – Dave Orr
                May 5 '11 at 22:29













              • On further investigation, ':input[value=""]' isn't finding anything. Walking through with a debugger after I split out the attr() call onto another line via each() shows that it never gets there, so disabled is never getting set.

                – Dave Orr
                May 5 '11 at 22:59






              • 1





                @Dave: I suspect that if you change $(this).children to $(this).find, it'll work in either place.

                – Luke Dennis
                May 6 '11 at 20:26






              • 1





                @FelipeTadeo: It should, because it's not using the "input" selector, but rather ":input", which is a jQuery-specific way to target inputs, textareas, selects, etc. However, the [value=""] part of the selector may not work with textarea. Best way might be to use a filtering function, similar to this: .children(':input').filter(function(item){ return !!$(item).val(); /* untested */ })

                – Luke Dennis
                Jan 16 '13 at 0:00








              • 2





                Recent versions of jQuery include the prop method. They recommend using that method rather than the attr method to set the disabled attribute so @LukeDennis code should be updated to $(this).children(':input[value=""]').prop('disabled', true);

                – jdp
                Jan 6 '15 at 15:30
















              38














              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






              share|improve this answer


























              • That is really elegant... only it doesn't seem to work. What am I missing? In particular, on submission via http get so I can see what's going on, I still see something like 'api/userattributes/?action=read_by_user&name=&value=' where name and value were left blank, but still show up as submitting variables.

                – Dave Orr
                May 5 '11 at 22:29













              • On further investigation, ':input[value=""]' isn't finding anything. Walking through with a debugger after I split out the attr() call onto another line via each() shows that it never gets there, so disabled is never getting set.

                – Dave Orr
                May 5 '11 at 22:59






              • 1





                @Dave: I suspect that if you change $(this).children to $(this).find, it'll work in either place.

                – Luke Dennis
                May 6 '11 at 20:26






              • 1





                @FelipeTadeo: It should, because it's not using the "input" selector, but rather ":input", which is a jQuery-specific way to target inputs, textareas, selects, etc. However, the [value=""] part of the selector may not work with textarea. Best way might be to use a filtering function, similar to this: .children(':input').filter(function(item){ return !!$(item).val(); /* untested */ })

                – Luke Dennis
                Jan 16 '13 at 0:00








              • 2





                Recent versions of jQuery include the prop method. They recommend using that method rather than the attr method to set the disabled attribute so @LukeDennis code should be updated to $(this).children(':input[value=""]').prop('disabled', true);

                – jdp
                Jan 6 '15 at 15:30














              38












              38








              38







              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






              share|improve this answer















              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







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited May 14 '14 at 13:01









              Community

              11




              11










              answered May 5 '11 at 21:46









              Luke DennisLuke Dennis

              6,982154864




              6,982154864













              • That is really elegant... only it doesn't seem to work. What am I missing? In particular, on submission via http get so I can see what's going on, I still see something like 'api/userattributes/?action=read_by_user&name=&value=' where name and value were left blank, but still show up as submitting variables.

                – Dave Orr
                May 5 '11 at 22:29













              • On further investigation, ':input[value=""]' isn't finding anything. Walking through with a debugger after I split out the attr() call onto another line via each() shows that it never gets there, so disabled is never getting set.

                – Dave Orr
                May 5 '11 at 22:59






              • 1





                @Dave: I suspect that if you change $(this).children to $(this).find, it'll work in either place.

                – Luke Dennis
                May 6 '11 at 20:26






              • 1





                @FelipeTadeo: It should, because it's not using the "input" selector, but rather ":input", which is a jQuery-specific way to target inputs, textareas, selects, etc. However, the [value=""] part of the selector may not work with textarea. Best way might be to use a filtering function, similar to this: .children(':input').filter(function(item){ return !!$(item).val(); /* untested */ })

                – Luke Dennis
                Jan 16 '13 at 0:00








              • 2





                Recent versions of jQuery include the prop method. They recommend using that method rather than the attr method to set the disabled attribute so @LukeDennis code should be updated to $(this).children(':input[value=""]').prop('disabled', true);

                – jdp
                Jan 6 '15 at 15:30



















              • That is really elegant... only it doesn't seem to work. What am I missing? In particular, on submission via http get so I can see what's going on, I still see something like 'api/userattributes/?action=read_by_user&name=&value=' where name and value were left blank, but still show up as submitting variables.

                – Dave Orr
                May 5 '11 at 22:29













              • On further investigation, ':input[value=""]' isn't finding anything. Walking through with a debugger after I split out the attr() call onto another line via each() shows that it never gets there, so disabled is never getting set.

                – Dave Orr
                May 5 '11 at 22:59






              • 1





                @Dave: I suspect that if you change $(this).children to $(this).find, it'll work in either place.

                – Luke Dennis
                May 6 '11 at 20:26






              • 1





                @FelipeTadeo: It should, because it's not using the "input" selector, but rather ":input", which is a jQuery-specific way to target inputs, textareas, selects, etc. However, the [value=""] part of the selector may not work with textarea. Best way might be to use a filtering function, similar to this: .children(':input').filter(function(item){ return !!$(item).val(); /* untested */ })

                – Luke Dennis
                Jan 16 '13 at 0:00








              • 2





                Recent versions of jQuery include the prop method. They recommend using that method rather than the attr method to set the disabled attribute so @LukeDennis code should be updated to $(this).children(':input[value=""]').prop('disabled', true);

                – jdp
                Jan 6 '15 at 15:30

















              That is really elegant... only it doesn't seem to work. What am I missing? In particular, on submission via http get so I can see what's going on, I still see something like 'api/userattributes/?action=read_by_user&name=&value=' where name and value were left blank, but still show up as submitting variables.

              – Dave Orr
              May 5 '11 at 22:29







              That is really elegant... only it doesn't seem to work. What am I missing? In particular, on submission via http get so I can see what's going on, I still see something like 'api/userattributes/?action=read_by_user&name=&value=' where name and value were left blank, but still show up as submitting variables.

              – Dave Orr
              May 5 '11 at 22:29















              On further investigation, ':input[value=""]' isn't finding anything. Walking through with a debugger after I split out the attr() call onto another line via each() shows that it never gets there, so disabled is never getting set.

              – Dave Orr
              May 5 '11 at 22:59





              On further investigation, ':input[value=""]' isn't finding anything. Walking through with a debugger after I split out the attr() call onto another line via each() shows that it never gets there, so disabled is never getting set.

              – Dave Orr
              May 5 '11 at 22:59




              1




              1





              @Dave: I suspect that if you change $(this).children to $(this).find, it'll work in either place.

              – Luke Dennis
              May 6 '11 at 20:26





              @Dave: I suspect that if you change $(this).children to $(this).find, it'll work in either place.

              – Luke Dennis
              May 6 '11 at 20:26




              1




              1





              @FelipeTadeo: It should, because it's not using the "input" selector, but rather ":input", which is a jQuery-specific way to target inputs, textareas, selects, etc. However, the [value=""] part of the selector may not work with textarea. Best way might be to use a filtering function, similar to this: .children(':input').filter(function(item){ return !!$(item).val(); /* untested */ })

              – Luke Dennis
              Jan 16 '13 at 0:00







              @FelipeTadeo: It should, because it's not using the "input" selector, but rather ":input", which is a jQuery-specific way to target inputs, textareas, selects, etc. However, the [value=""] part of the selector may not work with textarea. Best way might be to use a filtering function, similar to this: .children(':input').filter(function(item){ return !!$(item).val(); /* untested */ })

              – Luke Dennis
              Jan 16 '13 at 0:00






              2




              2





              Recent versions of jQuery include the prop method. They recommend using that method rather than the attr method to set the disabled attribute so @LukeDennis code should be updated to $(this).children(':input[value=""]').prop('disabled', true);

              – jdp
              Jan 6 '15 at 15:30





              Recent versions of jQuery include the prop method. They recommend using that method rather than the attr method to set the disabled attribute so @LukeDennis code should be updated to $(this).children(':input[value=""]').prop('disabled', true);

              – jdp
              Jan 6 '15 at 15:30













              17














              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.






              share|improve this answer


























              • No - I think they are a figment of an over-imaginative mind.

                – ReggieB
                Sep 28 '17 at 7:23











              • This should be the accepted answer. The accepted answer basically checks the input value when initially rendered (which may change), this answer checks the live input value when submitted.

                – Hudri
                Nov 12 '18 at 13:49


















              17














              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.






              share|improve this answer


























              • No - I think they are a figment of an over-imaginative mind.

                – ReggieB
                Sep 28 '17 at 7:23











              • This should be the accepted answer. The accepted answer basically checks the input value when initially rendered (which may change), this answer checks the live input value when submitted.

                – Hudri
                Nov 12 '18 at 13:49
















              17












              17








              17







              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.






              share|improve this answer















              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.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Sep 28 '17 at 11:44









              Bob Stein

              7,11135174




              7,11135174










              answered Sep 11 '13 at 9:32









              ReggieBReggieB

              5,83833038




              5,83833038













              • No - I think they are a figment of an over-imaginative mind.

                – ReggieB
                Sep 28 '17 at 7:23











              • This should be the accepted answer. The accepted answer basically checks the input value when initially rendered (which may change), this answer checks the live input value when submitted.

                – Hudri
                Nov 12 '18 at 13:49





















              • No - I think they are a figment of an over-imaginative mind.

                – ReggieB
                Sep 28 '17 at 7:23











              • This should be the accepted answer. The accepted answer basically checks the input value when initially rendered (which may change), this answer checks the live input value when submitted.

                – Hudri
                Nov 12 '18 at 13:49



















              No - I think they are a figment of an over-imaginative mind.

              – ReggieB
              Sep 28 '17 at 7:23





              No - I think they are a figment of an over-imaginative mind.

              – ReggieB
              Sep 28 '17 at 7:23













              This should be the accepted answer. The accepted answer basically checks the input value when initially rendered (which may change), this answer checks the live input value when submitted.

              – Hudri
              Nov 12 '18 at 13:49







              This should be the accepted answer. The accepted answer basically checks the input value when initially rendered (which may change), this answer checks the live input value when submitted.

              – Hudri
              Nov 12 '18 at 13:49













              5














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





              share|improve this answer






























                5














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





                share|improve this answer




























                  5












                  5








                  5







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





                  share|improve this answer















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






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Oct 22 '12 at 9:44









                  Emil Lundberg

                  5,47743147




                  5,47743147










                  answered May 5 '11 at 22:43









                  forthehackofitforthehackofit

                  1,0121611




                  1,0121611























                      1














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








                      share|improve this answer
























                      • also for me two i think the selector not working

                        – Baha'a Odeh
                        Aug 13 '18 at 21:10
















                      1














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








                      share|improve this answer
























                      • also for me two i think the selector not working

                        – Baha'a Odeh
                        Aug 13 '18 at 21:10














                      1












                      1








                      1







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








                      share|improve this answer













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








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

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





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

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






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Jan 5 '16 at 15:24









                      Ken BrockertKen Brockert

                      384




                      384













                      • also for me two i think the selector not working

                        – Baha'a Odeh
                        Aug 13 '18 at 21:10



















                      • also for me two i think the selector not working

                        – Baha'a Odeh
                        Aug 13 '18 at 21:10

















                      also for me two i think the selector not working

                      – Baha'a Odeh
                      Aug 13 '18 at 21:10





                      also for me two i think the selector not working

                      – Baha'a Odeh
                      Aug 13 '18 at 21:10











                      0














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





                      share|improve this answer
























                      • @Luke just beat me to it with an almost identical answer, I prefer Luke's solution. :)

                        – Dean North
                        May 5 '11 at 21:55
















                      0














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





                      share|improve this answer
























                      • @Luke just beat me to it with an almost identical answer, I prefer Luke's solution. :)

                        – Dean North
                        May 5 '11 at 21:55














                      0












                      0








                      0







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





                      share|improve this answer













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






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered May 5 '11 at 21:54









                      Dean NorthDean North

                      3,57022329




                      3,57022329













                      • @Luke just beat me to it with an almost identical answer, I prefer Luke's solution. :)

                        – Dean North
                        May 5 '11 at 21:55



















                      • @Luke just beat me to it with an almost identical answer, I prefer Luke's solution. :)

                        – Dean North
                        May 5 '11 at 21:55

















                      @Luke just beat me to it with an almost identical answer, I prefer Luke's solution. :)

                      – Dean North
                      May 5 '11 at 21:55





                      @Luke just beat me to it with an almost identical answer, I prefer Luke's solution. :)

                      – Dean North
                      May 5 '11 at 21:55











                      0














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






                      share|improve this answer




























                        0














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






                        share|improve this answer


























                          0












                          0








                          0







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






                          share|improve this answer













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







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Sep 29 '17 at 12:50









                          Bob SteinBob Stein

                          7,11135174




                          7,11135174






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f5904437%2fjquery-how-to-remove-blank-fields-from-a-form-before-submitting%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Lallio

                              Futebolista

                              Jornalista