I am trying to get some html5 localstorage working but with no luck.
It’s not saving and when I click the “Click to Save” link I don’t get the alert on the function.
I’m I forgetting something here?
Here’s the full code below:
<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$(document).ready(function(){
loaddata(); //Load the saved data
function loaddata() {
$('#mydiv').val(localStorage.mydata);
}
function savedata() {
localStorage.mydata = $('#mydiv').val();
alert('Data Saved!'); //This is not showing up
}
});
</script>
</head>
<body>
<a href="#" onclick="savedata();">Click to Save</a>
<table>
<tr>
<td id="mydiv">0</td>
</tr>
</table>
</body>
</html>
You can’t access
savedatafrom the onclick handler of your link, because it’s wrapped in thedocument.readycall.Either move
savedataout of thedocument.readyor use jQuery to attach the click handler directly to the element.Or the other way
Here is a jsFiddle that fixes your errors, including trying to use
.val()on atdelement. It also changes the data to different values you can see if it is working or not.