Skip to content

Instantly share code, notes, and snippets.

@UndeadBaneGitHub
Created June 7, 2014 19:55
Show Gist options
  • Save UndeadBaneGitHub/c2451adb2187584b7c54 to your computer and use it in GitHub Desktop.
Save UndeadBaneGitHub/c2451adb2187584b7c54 to your computer and use it in GitHub Desktop.
jQuery toPlainObject
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>$title</title>
$styles
</head>
<body>
<h1>$title</h1>
<p>
<input type="text" id="txt" value="Hello, $title!" />
<input type="button" id="btn" value="hello" />
</p>
$scripts
</body>
</html>
$(function() {
$('#btn').on('click', function() {
alert($('#txt').val());
});
function addPropertyToExisting(property, newPropValue){
};
function itemToObject(item, obj, separatorForText) {
var retObj = obj || {};
if (item instanceof $) {
item.each(function () {
itemToObject(this, retObj);
});
} else if (item.hasOwnProperty("toObject")) {
var objectFromItem = item.toObject();
for (var property in objectFromItem) {
if (objectFromItem.hasOwnProperty(property)) {
//add the property to the big object
var propName = property;
var propIndex = 1;
while (retObj.hasOwnProperty(propName)) {
propName = property + propIndex.toString();
}
retObj[propName] = objectFromItem[property];
}
}
} else if ($(item).children().length) {
$(item).children().each(function () {
itemToObject(this, retObj)
});
} else { //it is just some node, we may only get text from it
var objText = (item.nodeName === "input" || item.nodeName === "textarea") ? $(item).val() : $(item).text();
if (retObj['text']) {
var localSeparatorForText = separatorForText ? separatorForText : " ";
retObj['text'] += localSeparatorForText + objText;
} else {
retObj['text'] = objText;
}
}
if (!obj) {
return retObj;
}
}
});
body {
background: #eee;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment