我如何使用 jQuery 的 form.serialize 但排除空字段 [英] How do I use jQuery's form.serialize but exclude empty fields
问题描述
我有一个包含许多文本输入的搜索表单 &通过 GET 提交的下拉列表.我想通过在执行搜索时从查询字符串中删除空字段来获得更清晰的搜索 url.
I have a search form with a number of text inputs & drop downs that submits via a GET. I'd like to have a cleaner search url by removing the empty fields from the querystring when a search is performed.
var form = $("form");
var serializedFormStr = form.serialize();
// I'd like to remove inputs where value is '' or '.' here
window.location.href = '/search?' + serializedFormStr
知道如何使用 jQuery 做到这一点吗?
Any idea how I can do this using jQuery?
推荐答案
我一直在查看 jQuery 文档 我认为我们可以在一行中使用 selectors:
I've been looking over the jQuery docs and I think we can do this in one line using selectors:
$("#myForm :input[value!='']").serialize() // does the job!
显然,#myForm 获取 ID 为myForm"的元素,但起初对我来说不太明显的是,#myForm 和 :input 之间需要 空格字符,因为它是 后代 运算符.
Obviously #myForm gets the element with id "myForm" but what was less obvious to me at first was that the space character is needed between #myForm and :input as it is the descendant operator.
:input 匹配所有输入、文本区域、选择和按钮元素.
:input matches all input, textarea, select and button elements.
[value!=''] 是一个非属性等过滤.奇怪(且有用)的事情是所有 :input 元素类型都具有值属性,甚至选择和复选框等.
[value!=''] is an attribute not equal filter. The weird (and helpful) thing is that all :input element types have value attributes even selects and checkboxes etc.
最后还要删除值为."的输入(如问题中所述):
Finally to also remove inputs where the value was '.' (as mentioned in the question):
$("#myForm :input[value!=''][value!='.']").serialize()
在这种情况下并列,即 将两个属性选择器放在一起,意味着一个 AND.使用逗号 意味着 OR.对不起,如果这对 CSS 人员来说很明显!
In this case juxtaposition, ie placing two attribute selectors next to each other, implies an AND. Using a comma implies an OR. Sorry if that's obvious to CSS people!
这篇关于我如何使用 jQuery 的 form.serialize 但排除空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!