我需要tp序列化一组输入元素,但我不能为我的生活找出这个简单的任务.
我可以使用以下方法成功迭代目标输入:
$("#tr_Features :input").each(function() {
...
}
Run Code Online (Sandbox Code Playgroud)
这是我的代码,不起作用:
var features = "";
$("#tr_Features :input").each(function() {
features += {$(this).attr("name"): $(this).val()};
}
Run Code Online (Sandbox Code Playgroud)
序列化整个表单不会给我我需要的东西.表单不仅仅包含这个输入子集.这似乎应该是一个相当简单的任务,但显然编程到周五下午的晚期并不是一件好事.
如果它有用,这是我要定位的表单输入:
<table cellspacing="0" border="0" id="TblGrid_list" class="EditTable" cellpading="0">
<tbody><tr class="FormData" rowpos="1">
<td class="CaptionTD ui-widget-content">Cable Family</td>
<td class="DataTD ui-widget-content" style="white-space: pre;"> <input type="text" value="" id="feature_id:8" name="feature_id:8"></td>
</tr>
<tr class="FormData" rowpos="1">
<td class="CaptionTD ui-widget-content">Material</td>
<td class="DataTD ui-widget-content" style="white-space: pre;"> <input type="text" value="" id="feature_id:9" name="feature_id:9"></td>
</tr>
<tr class="FormData" rowpos="1">
<td class="CaptionTD ui-widget-content">Thread Size</td>
<td class="DataTD ui-widget-content" style="white-space: pre;"> <input type="text" value="" id="feature_id:10" name="feature_id:10"></td>
</tr>
<tr class="FormData" rowpos="1">
<td class="CaptionTD ui-widget-content">Attachment Style</td>
<td class="DataTD ui-widget-content" style="white-space: pre;"> <input type="text" value="" id="feature_id:11" name="feature_id:11"></td>
</tr>
<tr class="FormData" rowpos="1">
<td class="CaptionTD ui-widget-content">Feature</td>
<td class="DataTD ui-widget-content" style="white-space: pre;"> <input type="text" value="" id="feature_id:12" name="feature_id:12"></td>
</tr>
<tr class="FormData" rowpos="1">
<td class="CaptionTD ui-widget-content">Comments</td>
<td class="DataTD ui-widget-content" style="white-space: pre;"> <input type="text" value="" id="feature_id:13" name="feature_id:13"></td>
</tr>
Run Code Online (Sandbox Code Playgroud)
编辑:
如果我正确理解你的问题,这将为你提供你想要的json对象.
请注意,它需要json2库.
var features = {}; // Create empty javascript object
$("#tr_Features :input").each(function() { // Iterate over inputs
features[$(this).attr('name')] = $(this).val(); // Add each to features object
});
var json = JSON.stringify(features); // Stringify to create json object (requires json2 library)
Run Code Online (Sandbox Code Playgroud)
感谢R0MANARMY在问题中指出了预期的json格式.
有没有理由你不使用jQuery的.serializeArray()功能?您可以在元素的子集而不是整个表单上运行它.
$("#tr_Features :input").serializeArray();
Run Code Online (Sandbox Code Playgroud)
来自文档:http://api.jquery.com/serializeArray/
.serializeArray()方法创建一个JavaScript对象数组,可以编码为JSON字符串.
所述.serializeArray()方法可作用已选定的个别形式的元件,诸如jQuery对象上<input>,<textarea>和<select>.
显然,我所创造的只是一个漫长而艰难的对象.这听起来比它应该的更糟,但这是真的.我需要做的就是使用index/key的name属性和val()作为值.
var data = new Object();
$("#tr_Features :input").each(function() {
data[$(this).attr("name")] = $(this).val();
});
return data;
Run Code Online (Sandbox Code Playgroud)
这很有效.谁知道?!真的很简单.你们伸出援助之手向我伸出一只向上箭头,我打电话给周五.干杯!
| 归档时间: |
|
| 查看次数: |
24752 次 |
| 最近记录: |