Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we store a string in localStorage?

I'm learning javascript, xml, and html. For a homework assignment, I need to retrieve some data from some nodes of a XML file, concatenate the data, and store the concatenated string in localStorage. I am having trouble in storing the concatenated string in localStorage. I believe the issue is in these two lines -

var s_data = localStorage[students];
$("#clickme").text("Students' first names: " + s_data);

Can someone take a look and give me some tips on how to fix it? Thank you in advance for your help.

    <!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <title>HWK</title>
    <meta charset="UTF-8">  
</head>
<body>
    <div id="clickme" onclick="startAjax()">Click me to see all the students' first names</div>
    <script>
    function startAjax(){
      $("#clickme").text("Calling server");
      $.ajax({url:"hwk.xml",    
      success:callbackFunction, error:errorFunction});
    }

    function callbackFunction(data,info)
    {
        var students = $(data).find("student first_name");

    try {
    if (students && students.length)
      {
        var s_data = localStorage[students];    
        $("#clickme").text("Students' first names: " + s_data);
              }
    }
    catch (e) {
      if (e != window["localStorage"])
        alert("No local storage. Should use cookie instead.");

    }
     }

    function errorFunction(data,info){
    $("#clickme").text("error occurred:"+info);
    }
    </script>
</body>
</html>
like image 335
user2203774 Avatar asked Jul 16 '13 03:07

user2203774


1 Answers

You can use the setItem() to set a value to the localStorage and getItem() to retrieve it

Ex:

localStorage.setItem('mykey', 'somevalue')

Demo: Fiddle

like image 185
Arun P Johny Avatar answered Oct 22 '22 16:10

Arun P Johny