[英]Serializing a form with dynamic keys
I am looking for a better way to serialize a form with input pairs; 我正在寻找一种更好的方法来序列化带有输入对的表单。 one input is for the key, another is for the value. 一个输入用于键,另一个输入用于值。 Whoever is using this form could opt to add more key-value input pairs. 任何使用此表单的人都可以选择添加更多的键值输入对。
I currently have this fiddle to serialize the form, but I am not convinced this is the best/optimal/readable way. 我目前有这个小提琴来序列化表格,但是我不相信这是最佳/最佳/可读的方式。 Are there any library or method I'm missing that would make this code better? 我缺少任何可以使此代码更好的库或方法吗?
Code as follows: 代码如下:
HTML: HTML:
<div>
<form>
<span>
<input type="text" class="key" id="key1"/><input type="text" class="value" id="value1"/>
</span>
</form>
</div>
<a href="#" id="add">Add</a>
<a href="#" id="serialize">Serialize</a>
<div id="serialized-string"></div>
JavaScript : JavaScript:
$(document).ready(function(){
var numberOfPairs = $('.key').length;
$('#add').on('click', function () {
numberOfPairs += 1;
$('div > form').append('<span><input type="text" class="key" id="key'+numberOfPairs+'"/><input type="text" class="value" id="value'+numberOfPairs+'"/></span>');
});
$('#serialize').on('click', function () {
var serialized = "";
for(var x = 1; x <= numberOfPairs; x +=1) {
var keyValuePair = $('#key'+x).val() + "=" + $('#value'+x).val();
if(serialized.length > 0) {
serialized += "&" + keyValuePair;
} else {
serialized += keyValuePair;
}
}
alert(serialized);
});
});
and CSS 和CSS
span {
display: block;
}
Also, I am not sure if I should properly encode this to URI... 另外,我不确定是否应该将其正确编码为URI ...
You can use .serialize : 您可以使用.serialize :
The .serialize() method creates a text string in standard URL-encoded notation. .serialize()方法以标准的URL编码表示法创建文本字符串。 It can act on a jQuery object that has selected individual form controls, such as <input>, <textarea>, and <select> 它可以作用于已选择单个表单控件(例如<input>,<textarea>和<select>)的jQuery对象。
Example: 例:
$('#serialize').on('click', function () {
alert($('form').serialize());
});
But this assumes you've provided a name for your form elements. 但这假设您已经为表单元素提供了名称。
<input type="text" class="key" name="key1" id="key1"/><input type="text" class="value" id="value1" name="key2" />**strong text**
See http://jsfiddle.net/s2tyS/1/ 参见http://jsfiddle.net/s2tyS/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.