HTML5 Storage / JQuery Not saving Data

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>

Answers


You can't access savedata from the onclick handler of your link, because it's wrapped in the document.ready call.

Either move savedata out of the document.ready or use jQuery to attach the click handler directly to the element.

$(document).ready(function() {

    loaddata(); //Load the saved data

    function loaddata() {
        $('#mydiv').html(localStorage.mydata);

    }
});

function savedata() {
    localStorage.mydata = $('#mydiv').html();
    alert('Data Saved!'); //This is not showing up
}

Or the other way

<a href="#" id="savebtn">Click to Save</a>

$("#savebtn").click(function() {
    localStorage.mydata = $('#mydiv').val();
    alert('Data Saved!'); //This is not showing up
});

Here is a jsFiddle that fixes your errors, including trying to use .val() on a td element. It also changes the data to different values you can see if it is working or not.


Need Your Help

When invoking clock_gettime() may the returned tv_nsec field actually exceed a second?

c linux glibc libc

When you invoke clock_gettime() it returns a timespec structure.

dynamic table references with Excel VBA

excel vba excel-vba

I have an Excel table called "groups" where the headers are group names. In the column below the group name are the members of that specific group.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.