If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Hybrid View

Creating new JS objects from form for local storage

Hello,

I'm a beginner at JavaScript and for a school project, I need to build a mobile web application using HTML, CSS and JavaScript. I realise what I plan to do would be better off using PHP, but since we haven't learnt that yet I'll have to stick to JS for now. For this application, I need to store data using forms and local storage. The user will add people to a locally stored "database" (for lack of better words), and can on a different form add items that can be bound to one person or several persons.

I've tried to do as much research and attempts as possible, but am now stumped. This is where I'm at now: The persons should be stored as objects, and I've been advised to have the items stored as arrays. When the user adds a new person, a new object should be created. I just can't figure out how exactly to do that. I've been unable to find the solution that fits my problem. I haven't even started on the array part yet, since I'm stuck on adding the object. Sounds simple enough when reading about it, but still I have some problems with it. Therefore I turn to you for help.

So, the Big Question: How do I successfully create new objects that are stored in local storage, when I click an Add button, while not overwriting each other?

(Please note that more form fields and thus more object properties will be added, for testing purpose I've only been working with the name property.)

I've been lurking a bit on this forum, time for me now to ask the question and hopefully someone else can benefit from this as well. =D

Look at the documentation for JSON.parse and JSON.stringify. These will allow you to turn simple arrays and objects into strings and back again. You can turn your data into a string suitable for recording in localStorage.

Since you're more than likely going to be storing more than one person in the database, you'll probably want to save them in an array. A good approach would be to load the objects from localStorage to populate the array instantly. Do some research on arrays (like pop, push, etc) and especially loops. Here is some code which will hopefully help you understand a bit more: