I have a Edit/Details form which has 4 user related fields. On click of Save, I save the edited fields to local storage (if supported) and display the same values in the Details view.
Below is the code which does that;
var UserDataObj = {
name:"John",
email:"john@example.com",
phone:"9999999999",
desc:"some description"
}
/**
* Check HTML5 Local Storage support
*/
function supports_html5_storage()
{
try {
window.localStorage.setItem( 'checkLocalStorage', true );
return true;
} catch ( error ) {
return false;
};
};
/**
* Save form data to local storage
*/
function saveFormData()
{
if (supports_html5_storage())
{
$(".formFieldUserData").each(function(){
UserDataObj[$(this).attr("name")] = $(this).val();
});
localStorage.setItem('UserDataObj', JSON.stringify(UserDataObj));
}
}
/**
* Set field values based on local storage
*/
function setFormFieldValues()
{
if (supports_html5_storage())
{
var retrievedUserDataObj = JSON.parse(localStorage.getItem('UserDataObj'));
if(retrievedUserDataObj)
{
$(".formFieldUserData").each(function(){
var currentKey = $(this).attr("name");
var retrievedValue = retrievedUserDataObj[$(this).attr("name")]
$("#"+currentKey).val(retrievedValue);
$("#"+currentKey+"Txt").html(retrievedValue);
});
}
else
{
$(".formFieldUserData").each(function(){
var currentKey = $(this).attr("name");
var userDataObjValue = UserDataObj[$(this).attr("name")]
$("#"+currentKey).val(userDataObjValue);
$("#"+currentKey+"Txt").html(userDataObjValue);
});
}
}
else
{
$(".formFieldUserData").each(function(){
var currentKey = $(this).attr("name");
if ($(this).val() != "")
{
var fieldValue = $(this).val();
$("#"+currentKey).val(fieldValue);
$("#"+currentKey+"Txt").html(fieldValue);
}
else
{
var defaultuserDataObjValue = UserDataObj[$(this).attr("name")];
$("#"+currentKey).val(defaultuserDataObjValue);
$("#"+currentKey+"Txt").html(defaultuserDataObjValue);
}
})
}
}
My question is;
- This is a completely working code. But is there any further that I can do as far as best coding practices go.
- Also performance wise, can I do anything to improve the overall code ?
Thank you.