Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Localstorage Add / Remove variables to the table

Hi,

I've created 2 inputs

<input type="text" id="player">
<input type="text" id="team">

I want to append the value of them inside of a table. That's the east part... But I want to use the localStorage so if the page is refreshed the details will be saved.

So for example i have this code:

    $(document).ready(function () {

            var $tournament = $('#tournament');        

            if(localStorage.getItem("#tournament")) {
                $tournament.html(localStorage.getItem("#tournament"));
            }
            $('button').click(function () {        
                $tournament.append('<tr><td>' + $('#player').val() + '</td><td>' + $('#team').val() + '</td>><td id="clear">Remove</td></tr>');             
                localStorage.setItem("#tournament", $tournament.html());
            });

            $('#clear').click(function(){
                localStorage.removeItem('#tournament tr');
            });
        });

the localStorage works fine, but I want when I click on the remove text, the tr row will be remove

2 Answers

Hey Maor Tzabari,

I edited your post so that the code will render better. You can refer to the Markdown Cheatsheet, go in and edit your post, or refer to the image at the bottom for how I did that.

code

What's going on when the clear button is clicked is that you're attempting to remove the value stored in the localStorage variable named "#tournament" but you've added a tr to the string to try to remove the table row. What you need to do is just remove the "#tournament" variable and then set the HTML inside the table with the id of "tournament" to whatever the default initial value is. If you post your HTML code, I can get a better feel for what you're doing with the table, but without that, I'll just assume that the table is blank and you're only adding the one table row so you can set it's html to be an empty string.

Here is what you'd want to do:

 $('#clear').click(function(){
    localStorage.removeItem('#tournament');
    $("#tournament").html("");
});

You know what..? I'm doing those 3 backticks all the time and it never works fine, should I break with the enter key after those 3 backticks?

Anyway, this is my code that I need help with: http://sourcenload.com/localstorage/

I would appreciate it so much if you would help me with that, I'm trying to understand this localstorage, I asked this question 4 times in stack overflow, and nobody understand me.

Thank you so much for helping

Yea, you want to add spaces above and below whole the 3 backticks when you paste in code. Also, make sure there is no text on the line with 3 backticks unless it is in the opening 3 backticks and the text can only be the language you are using i.e. "javascript", "html", "css" etc.

I figured out a good solution for you that is dynamic and will allow you to delete individual rows of players and teams. First, I added an id of "submit" to your submit button so that we can target that specific button's click property in an easy way. Then, I changed up the code some to add a button that says "Remove" in the last table cell and gave it a class of "clear". Once you click remove, it will remove only that row it is on using the method "closest()" which will target the closest table row, which is the table row that the button is located on.

            var $tournament = $('#tournament');        

            if(localStorage.getItem("#tournament")) {
                $tournament.html(localStorage.getItem("#tournament"));
            }

            $('#submit').click(function () {       
                         //Added a button with class of clear instead of a table row with id of clear
                $tournament.append('<tr><td>' + $('#player').val() + '</td><td>' + $('#team').val() + '</td><td><button class="clear">Remove</button></td></tr>');         
                localStorage.setItem("#tournament", $tournament.html());
                        $('.clear').click(function(){
                            //Remove the closest table row using the "this" object and closest()
                    $(this).closest("tr").remove();
              localStorage.setItem('#tournament', $tournament.html());
            });
            });
            $('.clear').click(function(){
                            //Remove the closest table row using the "this" object and closest()
                    $(this).closest("tr").remove();
              localStorage.setItem('#tournament', $tournament.html());
            });

First, How do I clean all the previous localstorage? I've tried to add a line like

    $('#tournament').clear();
     $('#tournament').removeItem();

None of them work for me.

Secondly, I don't really understand why do I have to setItem after we remove the tr (row), and also I'm trying to understand this statement:

    if(localStorage.getItem("#tournament")) {
                $tournament.html(localStorage.getItem("#tournament"));
            }

Why would you want to completely clear the localStorage? If you're saving the names of Players and Teams, you'd want to keep whatever players and teams haven't been removed. When you are using local storage, you must specify what you are removing. So you have to do:

localStorage.removeItem("#tournament");

Secondly, I didn't put that code in there. You had that code already in there. So, did you copy and paste this code from somewhere? What you did when you put that into your program was set up the table with the information retrieved from the variable called "#tournament" that is in localStorage if it is available.

The reason why you are using setItem in that clear function is so that it sets that "#tournament" variable to the new data with that table row removed.

Imagine that the "tournament" table currently contains the following data:

<tbody>
<tr><td>Marcus</td><td>Blue Jays</td><td><button class="clear">Remove</button></td></tr>
<tr><td>Moar</td><td>Giants</td><td><button class="clear">Remove</button></td></tr>
</tbody>

Now, let's say I click clear on the "Remove" button that's beside Marcus' information. First, $(this).closest("tr").remove(); removes that table row from the DOM so that now the HTML looks like this:

<tbody>
<tr><td>Moar</td><td>Giants</td><td><button class="clear">Remove</button></td></tr>
</tbody>

But, if we were to only have that line and not set the value for the variable "#tournament" to the new HTML, when we refresh the page we would still see Marcus' information because it is getting that data from local storage. So, what we do is set the variable "#tournament" to that new HTML so that when we do refresh the page, we only have the data that is still there.

You must also realize that the "#tournament" you call with localStorage and the "#tournament" you are using with jQuery are two completely separate entities. The "#tournament" within localStorage is a variable whereas "#tournament" in your jQuery selector $("#tournament") is a jQuery object that has selected the element with the id of "tournament". I would recommend changing the variable name in localStorage to something like "tournamentHTML" so that it won't be confusing to you.

I also edited the answer to include the clear function outside of the submit. The reason why it is on there twice is to allow you to clear the data regardless of whether it was just appended or you came back later on and wanted to remove the data.

I wanted to clear that because it remember my previous code entries : ) you know.. the localStorage inputs that I've put before i used your code has been saved...

I know that the if section was already in my code, someone helped me with that and I just thought you could explain it to me, never mind, I'll just read it again and again until I will understand it.

I just have another question after that, What If i would like that this data will be save in every browser and every computer, just like database, Is it possible with localStorage? or will I need to start the MySQL course , haha :)

I'm just going by what you posted. I can naturally assume that if you're using local storage and inputting individual table rows into your table, that you wouldn't want to wipe out an entire table just to delete one entry. It wouldn't make sense to wipe out the entire table just to delete one row of information.

What that if statement is doing is first checking if the variable "#tournament" exists in localStorage. If it does, the code is executed. The code in the if statement is setting the HTML contents of the table to be whatever is stored in that variable. So, each time you are clicking that submit button, you are adding the row with the constructed data to the existing data with that append() method. And then you are setting the localStorage variable to that new information so that when you reload the page, you can still see all of the entries you've put into the table.

Now, if you want this data to be stored in a location where everyone can access it, you would need something like MySQL or another database in order to store the data so that everyone can get access to it. localStorage does exactly as its name suggests: it stores data locally.

Did that help clear up some confusion?

I know it is possible with MySQL, I was just learning jQuery and I thought just for practice I can build it, something more simple than MySQL.

You first paragraph is like a tricky method that I've meant to create this thing with the localStorage, But I guess your suggestion is to try the MySQL. OK, Thanks a lot!

jQuery is an absolutely fantastic (and in my opinion a must have) for dealing with client side programming and even interacting with a server. So, you should absolutely keep on learning jQuery. But, if you want to be able to store data that can be accessed by many people (and not easily tampered with), you should go with MySQL (or another database interface) and a server side programming language.

localStorage is very neat, and I used it in my first quite large jQuery project which is this calculator program here. If you play around with that, you can see that you can colorize your calculator however you wish, and localStorage is responsible for saving your settings so that you can come right back to it after closing the window/browser and have your settings exactly as you had them before. If you're using Chrome or Firefox, you can press Ctrl + U (if on Windows/Linux, not sure of command for Mac) and see the source of the page. There aren't many comments yet, but I plan on making it more developer friendly in the next day or so.

What you have to do is ask yourself how this program is gonna be used. If you want users to be able to store their own data that doesn't necessarily need to be persistent, you can use localStorage. But, if that data needs to be persistent, you should store it on a server with, say, MySQL and PHP.

The reason why you would want to store data on a server is that the client PC is a far more volatile area than a server. Servers don't change nearly as often as user's PCs. Users change software, OS's, and even PCs whenever they feel the need to, and that is perfectly fine, of course. So, we have to work around that, and the only way around that is to store data that has to be persistent in a remote location and then allow them to access it instead of storing it on their local machine.

Does that make sense?

Well if you shared already your project, i will show you mine: http://oritzio.com/pes2015/register.html

have a look what happens when you entering a name and choosing a team : )

I see. I like the layout and everything. It looks great! Did you take a look at the source of my page? lol took a look at your source, and you have some PHP code on the site. But just to let you know, PHP code only works on a page with at least a .php extension. If your page has any type of HTML extension, it won't execute the PHP code. So your register.html page won't execute that PHP code.

You might also want to put a <noscript> element on the page that will render if someone has JavaScript disabled since that register page is heavily reliant on JavaScript. Here is what I have on mine:

    <noscript>
        <h1 style="font-size: 2em; text-align: center; color: white;">This application requires JavaScript to be enabled in order to function properly.  Please re-enable JavaScript and then refresh the page.</h1>
    </noscript>

You're talking like I'm a beginner or something : ) First, I don't have PHP code on this page Second, if I would have PHP code on my page you couldn't see it anyway because PHP is a server side

I saw your page, I guess you have more knowledge of localStorage than I have :) the last 2 month I didn't really know jQuery or Javascript, I'm a web designer and I'm more familiar with HTML CSS stuff, But I've got to say that I forced my self and I'm trying really hard to learn it well. I have a lot of jQuery questions and I'm trying to learn it by watching those tutorials and posting here questions.

Recently I've build (just for practice) a vertical ticker with jQuery You know this vertical slider of the news, you probably familiar with that, Anyway I searched online for stuff like that, and I saw that all of that websites which offer this plugin to download is really crap, like it's not responsive, hard to use, and a lots of code.

I wrote this in like 7 lines with jQuery, this is awesome, I like it!

First, there's no reason to take offense to anything. Whenever I explain things, I go in armed with very little to no knowledge about how much you already know, so I explain things with as much detail as I can. Again, I don't know what you know and don't know. Do you take offense to the teachers in the videos explaining things in great detail? If you answered no, then you shouldn't take offense to someone else explaining things in great detail. We are typing in a forum, and not discussing things in a more active format. If we were talking, I could ask you if you know how to view the source of a page. But, since we're on a forum, I just go ahead and include how to do it just in case you don't know how. It would waste a serious amount of time for me to ask you if you know how to do something, then wait around for a response, and then ask if you know how to do something else, and keep repeating that process. So, please, try not to take offense when someone goes into detail about things.

Secondly, yes you do have PHP code on your page. PHP is a server side language, that is correct, but if it is on an HTML page, it won't do anything with the page itself; it will, however, still be shown in the source of the page. If your register page had a .php extension (or another php extension), I would not be able to see the PHP code. But since the PHP code is on an HTML page, I can see it, just as anyone else can. If you press Ctrl + U and view the source of your register page, you will a see little section of PHP code. It is right below your script in the head element.

By the way, here is a screenshot I took of the source of your page:

screenshot

Oh you right, sorry about that .. But this code as nothing to do with my code, I tried one time to do something with that ... I should remove that

LIsten, you need to be more receptive to feedback and critique. You've done quite a bit of arguing with me since I first started commenting on this thread. And all I've done is attempt to help you, but you've made that quite difficult for me. If you're going to end up being a developer and working with a team, you will want to work on being more receptive to others' suggestions and ideas.

I'm sorry, I didn't mean it Thank you for helping me, I really appreciate that!

You're welcome, Maor. I wish you many days of happy coding, sir!

Thank you, and sorry again I would like to ask you more questions about function with javascript, Is there a way I can contact you via Email?

If not, that's ok, I don't want to be annoying, I'm just trying to learn functions and it seems that only this part is really hard for me to understand

Sure! No problem. You can email me at parsons_marcus@yahoo.com.