How can I remove empty fields from my form in the querystring?

后端 未结 6 1566
滥情空心
滥情空心 2020-12-16 11:17

I have a simple form with four inputs. When I submit my form, I want to use the GET http method.

For the example :

aaa : foo
bbb : ____
ccc : bar
ffffd         


        
6条回答
  •  再見小時候
    2020-12-16 11:32

    With JQuery:

    $('#form').submit(function (e) {
      e.preventDefault();
    
      var query = $(this).serializeArray().filter(function (i) {
        return i.value;
      });
    
       window.location.href = $(this).attr('action') + (query ? '?' + $.param(query) : '');
    });
    

    Explanations:

    • .submit() hooks onto the form's submit event
    • e.preventDefault() prevents the form from submitting
    • .serializeArray() gives us an array representation of the query string that was going to be sent.
    • .filter() removes falsy (including empty) values in that array.
    • $.param(query) creates a serialized and URL-compliant representation of our updated array
    • setting a value to window.location.href sends the request

    See also this solution.

提交回复
热议问题