Created
June 7, 2014 19:55
-
-
Save UndeadBaneGitHub/c2451adb2187584b7c54 to your computer and use it in GitHub Desktop.
jQuery toPlainObject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(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; | |
} | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
body { | |
background: #eee; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment