Is there any better way to implement the below code
<form id="myform" onsubmit="return saveUserData('firstname','lastname');" method="post">
function saveUserData() {
createJSONString(arguments);
return false;
}
function createJSONString(arguments) {
var userDetails = "{";
for (i = 0; i < arguments.length - 1; i++) {
userDetails += '"' + arguments[i] + '":' + '"' +document.getElementById(arguments[i]).value + '",';
}
userDetails += '"' + arguments[i] + '":' + '"' + document.getElementById(arguments[i]).value + "}";
alert(userDetails);
}
Basically the function saveUserData is called from the form submit button. So the idea is to passs parameters to the function and create a JSON like string so that i can store it in the localStorage variable of Chrome and Firefox. The Idea is not to fail OCP because in future if we add middle name the JavaScript code need not change only the HTML will change.
Is there any better way to implement this?
Thanks
you can make JSON string using json.stringify method.
using json library, chrome and ff has build in this method.
http://json.org/
first you have to make javascript object for data like this.