7

I need to store data temporarily at the client-side to allow users to add, edit or delete items without having to query the server for each of these actions; just when the user finishes adding items and clicks on the Add button, the list is sent to the server to be saved permanently.

This image describes what I want to achieve. I know I have to use arrays in JavaScript, but I don't know how to create one to store objects (in this case Detail which contains :id, price and description).

I hope you can help me out. Thanks in advance. PS: I'm using JSP and... sorry for my English

  • you can use array of objects like jsp , i will provide you example soon. – kobe Dec 01 '10 at 22:47
  • see this example...http://bytes.com/topic/javascript/answers/512361-array-objects – kobe Dec 01 '10 at 22:48
  • if you are interacting with the backend through ajax , jsonp is the best option to send array of objects – kobe Dec 01 '10 at 22:54

3 Answers3

13

Sure, since it's a table it makes sense to have an array of objects. Note that an object is surrounded by curly braces and an array is surrounded by brackets:

var myArray = [];  // Initialize empty array
var myObject = {}; // Initialize empty object

This should accomplish what you need:

// Initialize variables
var newEntry, table = [];

// Create a new object
newEntry = {
  id: '',
  price: '',
  description: ''
};

// Add the object to the end of the array
table.push(newEntry);

Which is the same as this:

// Initialize array
var table = [];

// Create object and add the object to the end of the array
table.push({
  id: '22',
  price: '$222',
  description: 'Foo'
});

You can now access properties like this: table[0].id; // '22'

On modern browsers, if you want the data to persist across sessions (like cookies) you could use the sessionStorage or localStorage objects.

When you want to send the data to the server, you'll send a JSON version of the table across the wire:

var data = JSON.stringify(table);
David Calhoun
  • 8,315
  • 4
  • 30
  • 23
  • 2
    Probably worth mentioning that `JSON.stringify` is not a standard function on the majority of installed browsers out there, and to be sure it's there the OP should use a JSON library like [json2.js](https://github.com/douglascrockford/JSON-js). – T.J. Crowder Dec 01 '10 at 23:07
5

You can create an Array of your custom Detail objects pretty easily with object literals:

var details = [];
details.push({id:'abc1234', price:999.99, description:'Tesla Roadster'});
details.push({id:'xyz5678', price:129.99, description:'Land Rover'});

Then you can post your data to the server when the user clicks "Add."

Rob Sobers
  • 20,737
  • 24
  • 82
  • 111
1

Sounds like a good job for JSON.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176