Form Get Method: prevent empty fields from submittion in query string

北城余情 提交于 2019-12-01 08:15:54

问题


I am developing a search form.

Search Form has 2 parts, First simple search with some select, input, and submit button. Second contains many select, check box, radio, input and submit button.

I am using GET method as i want all fields in query string like. example.com/cars-parts/cars-for-sale/?country=205&city=19&cars_category=462

But the issue is if user don't select some fields(because he donot want to apply this criteria) a lot of empty fields and make query string too long.

Problem:

I want to remove (disable or whatever needed) all empty fields before form submission, so that query string includes only fields having value.

NOTE: Only suggest using Form Get Method. In Past i was using POST method and no values were passed in query string, but now i want values in query string.

Thank you for reading.


回答1:


You can bind a function on the form submit event and remove/disable all input with an empty value. Like this :

your_form.submit(function() {
    your_form.find('input').each(function() {
        var input = $(this);
        if (!input.val()) {
            input.remove(); // or input.prop('disabled', true);
        }
    });
});



回答2:


Try using the following in your $(function(){ ... }) section:

$('form').submit(function(){$('input[value=]',this).remove();return true;})

this will remove any empty input elements from your form before submitting it. You can of course modify it to include also non-selected selector boxes etc.




回答3:


I think you have to validate all those fields before including into the .get() method and do not include to the .get() method those inputs that has no values.



来源:https://stackoverflow.com/questions/17829379/form-get-method-prevent-empty-fields-from-submittion-in-query-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!