dcsimg
www.webdeveloper.com
Results 1 to 2 of 2

Thread: Javascript Array problem

  1. #1
    Join Date
    Sep 2012
    Posts
    1

    Javascript Array problem

    Hello,

    I have a simple form which when submitted, creates an object containing the form data then adds this object to an array. The array then gets added to the web storage. When the form is submitted again, the array should be retrieved from the web storage and the new object (containing the latest submitted values) is added to the array.

    However, my array 'fixtures' seems to be re-initialising each time and the copy which is stored in the web storage contains null values instead of the populated objects.

    Where am I going wrong please?


    Here is my code:

    Javascript:

    var fixtures=new Array();
    i = 0;

    function fixture(homeTeam, awayTeam)
    {
    this.homeTeam=homeTeam;
    this.homeTeamShort=new String(this.homeTeam).substr(0,4);
    this.awayTeam=awayTeam;
    this.awayTeamShort=new String(this.awayTeam).substr(0,4);
    //alert(this.homeTeamShort+" "+this.awayTeamShort);
    }

    function createFixtures(){

    var homeTeam=document.forms[0]["home"].value;
    var awayTeam=document.forms[0]["away"].value;
    var myFixture = new fixture(homeTeam, awayTeam);

    if(typeof(Storage)!=="undefined")
    {
    // Yes! localStorage and sessionStorage support!

    var retrievedObject = localStorage.getItem('fixtures');


    //retrievedObject = JSON.parse(retrievedObject);

    if(retrievedObject==null)
    {
    alert("nothing yet");
    fixtures[0] = myFixture;
    //localStorage.setItem('fixtures', JSON.stringify(fixtures));
    localStorage.setItem('fixtures', fixtures);

    }else
    {
    i=retrievedObject.length;
    fixtures[i] = myFixture;
    //localStorage.setItem('fixtures', JSON.stringify(fixtures));
    localStorage.setItem('fixtures', fixtures);
    i++;

    }

    }
    else
    {
    // Sorry! No web storage support..
    }


    }

    HTM form:
    <form name="fixture" onSubmit="return createFixtures()" method="post">

    <input type="text" name="home" size="20" placeholder="home side" required title="please add home team name"/> v <input type="text" name="away" size="20" placeholder="away side" required title="please add away team name"/>

    <input type="submit" value="Submit" />
    </form>

  2. #2
    Join Date
    Jul 2008
    Location
    urbana, il
    Posts
    2,787
    you have the proper lines commented out; the ones that JSON.stringify/parse the object to/from a string that localStorage can store...

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles