My problem is in my current code
it doesn't work
current output: http://jsfiddle.net/4GP2h/50/
My problem is in my current code
it doesn't work
current output: http://jsfiddle.net/4GP2h/50/
There are many things going on here:
You've multiple elements with id
gender, making your html invalid.
You can't store an array directly into localStorage
you need to stringify() it before inserting and parse() it after retrieving.
The localStorage.setItem()
function takes two parameters, the name (key) of the data to be stored and the actual data (value)
You're calling it with single parameter, like
localStorage.setItem(data) //Uncaught TypeError: Failed to execute 'setItem' on 'Storage': 2 arguments required, but only 1 present.
Which should be something like localStorage.setItem('info',data)
.
So that you can access the data upon page load using localStorage.getItem()
like localStorage.setItem('info')
.
(I had no previous experience with datatables, So i went through the examples and API documentation)
Once you have the data, you need to specify the data and columns options while initializing the table (this example demonstrates how to initialize dataTable with data from a js source.) as follows:
$('#myTable').dataTable({
"data": dataSet,
"columns": [{
"title": "Name"
}, {
"title": "Age"
}, {
"title": "Gender"
}, {
"title": "Action"
}]
// rest of the options
});
As you can see in the documentation, the data option accepts a 2D
array; So instead of saving a single record in an array, you've to create an array of arrays of all the records and save it in localStorage
The fiddle below lets you save one record (I'm wrapping it in another array for now) in localStorage
, retrieve and display it next time you visit.
As mentioned by Anthony in comments, it's better to save it once in unload event rather than trying to update localStorage
every time a record is created.