jQuery Plugin - 將欄位轉為JSON及還原
1 |
Abstract: This is a small plugin to covert all input(text, checkbox, radio), textarea, select values into a JSON string, and the values in JSON string can be restored to fields back latter.
專案裡有個小需求,要將<DIV>中的input(text, checkbox, radio), textarea, select轉成JSON字串傳回後端,稍後顯示時要能再還原回去。
jQuery本身提供可序列化整個Form為Query String的.serialize()函數,但我較想轉成JSON(因為在.NET端可以被還原),一時找不到現成的Plugin,心想不太難,就沒投資花時間去搜索,決定自己寫一個:
/*
==== jQuery Plugin - Fields To Json Ver 0.5 ====
** by Jeffrey Lee, http://blog.darkthread.net
Revision:
Ver 0.5 Beta 2009-08-23
- Convert all input, select and textarea to a JSON string
- Restore all input, select and textarea from a JSON string
*/
(function($) {
$.fn.fieldsToJson = function(prefix) {
if (!JSON || !JSON.stringify) {
alert("JSON is required!");
return "";
}
var obj = {};
this.find("input,select,textarea")
.each(function() {
if (!this.id) return; //Skip no id attribute
var fn = this.id;
//Filtered by prefix
if (prefix && fn.indexOf(prefix) == -1) return;
//Remove prefix
if (prefix) fn = fn.substr(prefix.length, fn.length - prefix.length);
var val = this.value + ""; //Avoid IE8 JSON bug
if (this.type == "checkbox" || this.type == "radio")
val = this.checked;
else if (this.type == "select-one")
val = this.selectedIndex;
else if (this.type == "select-multiple") {
var selected = [];
$(this).children().each(function(i) {
if (this.selected) selected.push(i);
});
val = selected.join(",");
}
obj[fn] = val;
});
alert(JSON.stringify(obj));
return JSON.stringify(obj);
}
$.fn.jsonToFields = function(jsonString, prefix) {
if (!JSON || !JSON.parse) {
alert("JSON is required!");
return "";
}
var obj = JSON.parse(jsonString);
this.find("input,select,textarea")
.each(function() {
if (!this.id) return; //Skip no id attribute
var fn = this.id;
//Filtered by prefix
if (prefix && fn.indexOf(prefix) == -1) return;
//Remove prefix
if (prefix) fn = fn.substr(prefix.length, fn.length - prefix.length);
if (obj[fn] == undefined) return;
var val = obj[fn];
if (this.type == "checkbox" || this.type == "radio")
this.checked = val;
else if (this.type == "select-one")
this.selectedIndex = val;
else if (this.type == "select-multiple") {
var selected = val.split(",");
var options = $(this).children();
options.filter(":selected").removeAttr("selected");
for (var i = 0; i < selected.length; i++) {
var opt = options[selected[i]];
if (opt) opt.selected = true;
}
}
else this.value = val;
});
}
})(jQuery);
應用時,要被轉換的欄位必須要有id屬性,指定或不指定id字首都可以。簡單測試程式如下:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="../js/json2.js" type="text/javascript"></script>
<script src="../js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="../js/jquery.filedsToJson.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("#btnSave").click(function() {
$("#taJson").val($("#dvBlock").fieldsToJson("f_"));
});
$("#btnRestore").click(function() {
$("#dvBlock").jsonToFields($("#taJson").val(), "f_");
});
});
</script>
</head>
<body>
<div id="dvBlock">
<input type="text" id="f_Text" />
<input type="radio" id="f_Radio" />
<input type="checkbox" id="f_Checkbox" />
<select id="f_SelectOne">
<option>A</option><option>B</option><option>C</option>
</select>
<select id="f_SelectMultiple" size="3" multiple >
<option>A</option><option>B</option><option>C</option>
</select>
<textarea id="f_TextArea" cols="20" rows="2"></textarea>
</div>
<input type="button" id="btnSave" value="SAVE" />
<input type="button" id="btnRestore" value="RESTORE" />
<div id="dvDisp">
<textarea id="taJson" cols="60" rows="4"></textarea>
</div>
</body>
</html>
有興趣的朋友可以Copy回去玩,如果發現有蟲蟲,記得再回饋給我,感謝!
Comments
# by Ammon
試試 serializeArray 這個 Method 順便看 Source code 偷學一下