javascript - 获取不为空的文本字段

标签 javascript jquery html query-string

假设我有一个这样的 HTML 结构:

<div class="container">
    <input type="text" class="userInfo" name="first_name1" value="First name 1" />
    <input type="text" class="userInfo" name="first_name2" value="First name 2" />
</div>

<div class="container">
    <input type="text" class="userInfo" name="first_name3" value="First name 3" />
    <input type="text" class="userInfo" name="first_name4" value="First name 4" />
</div>

当用户使用 jQuery 单击按钮时,如何获取所有不为空的文本字段?

一旦我得到它们,我想构造一个键值对字符串(用 & 连接)作为参数发送到 URL,例如:

"first_name1='First name 1&first_name2=First name 2'....

最佳答案

您可以使用 .filter() method查找所有包含值的 input 元素:

Example Here

var $fieldsWithValues = $('input').filter(function () {
    return this.value;
});

根据您的编辑,您可以使用 $.param() function 构造查询字符串:

Example Here

var params = {};
var $fieldsWithValues = $('input').filter(function () {
    return this.value.trim();
}).each(function () {
    params[this.name] = this.value;
});

console.log($.param(params));

以上将记录:

"first_name1=First+name+1&first_name2=First+name+2&first_name3=First+name+3&first_name4=First+name+4"

关于javascript - 获取不为空的文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33878906/

相关文章:

jquery - XPages: Bootstrap 验证器

css - 将图像添加到 svg 圆圈的底部

javascript - ajaxSetup beforeSend 仅在第一次单击按钮时被调用

javascript - 为 google-code-prettify 编译正则表达式

javascript - 在 jquery 中使用 'this' 的 If 语句语法

javascript - 使用 javascript 切换铁折叠

javascript - 加载页面时的 SlideToggle 等效项

javascript - 如果已经选中其他复选框,如何自动取消选中带有 javascript 的复选框?

javascript - 使用按钮删除 DIV

javascript - 创建字符串过滤器比较的最佳方法?