Reputation: 85
I have a table that is being generated automatically through the javascript application.
See test site here: https://hhpricetools.com/3d-wood-designer/
The summary table is on the last tab or you can click "view summary" at the top to get to it.
The table that is populated based on user choices looks like this:
<table id="summary-table" class="hhpt-summarytable"><tbody>
<tr><td>Style: <b>Side Lofted Barn</b></td>
<td> </td></tr>
<tr><td>Size: <b>10' x 16'</b></td><td> </td></tr>
<tr><td>Siding: <b>LP Smartside - Painted</b></td><td> </td></tr>
<tr><td>Wall Color: <b>Quest Gray #7080</b></td><td> </td></tr>
<tr><td>Trim Color: <b>White</b></td><td> </td></tr>
<tr><td>Roof: <b>Radiant Barrier LP Techshield</b></td><td> </td></tr><tr><td>
</td></tr></tbody></table>
That I am wanting to save to localStorage. For some reason I am getting "undefined" on the actual website above. The jsfiddle works fine, though. Why isn't it doing the same on the website?
var table_copy = $('#summary-table').html();
localStorage.setItem('table',table_copy);
console.log(localStorage.getItem("table"));
https://jsfiddle.net/ebryjz1q/
Upvotes: 0
Views: 205
Reputation: 3748
There are a few methods that you can do to make sure that your JavaScript loads after the DOM/HTML loads.
1. Use defer
You can use defer
to load the JavaScript after the HTML has loaded.
To do this, you can simply add the following attribute.
<script defer src="index.js"></script>
This should wait until the DOM has loaded before actually loading the JavaScript.
2. Add <script>
to <body>
Another solution is to add the script
tag to the end of the body
. This will make the JavaScript code load after all of the HTML has loaded.
3. Wait in JavaScript
You can also wait for the DOM to load in JavaScript (without JQuery).
There are two methods.
You can use the DOMContentLoaded
event listener. This will wait until the HTML has loaded. However, it won't wait for the images to load, stylesheets, etc.
To use this, you can use addEventListener()
.
window.addEventListener("DOMContentLoaded", () => {
// Code here will execute only after the DOM has loaded...
});
You can also use the load
event, which will load after the HTML has loaded, as well as images, stylesheets, etc.
You can use this listener with addEventListener
too.
window.addEventListener("load", () => {
// Code here will execute after everything has loaded...
});
You can do the same thing with the onload
event handler property.
window.onload = () => {
// Code here will execute after everything has loaded...
};
In conclusion, there are many ways to make the JavaScript wait until the DOM has loaded.
Upvotes: 1
Reputation: 87
You need to ensure the DOM has fully loaded before trying to store the HTML.
Try the following:
$('document').ready(function() {
var table_copy = $('#summary-table').html();
localStorage.setItem('table',table_copy);
console.log(localStorage.getItem("table"));
});
Upvotes: 0