0

Heres the problem. I am building a jquery program that lets me create and position divs on a drawing area. I need to keep track of the divs, their location, CSS proterties and other details. So, I am creating an object that contains an array of all these items for each div.

This is the code fragment for creating the object.

var divData= {items: [
{ID: "21", Block: "Block_01", posX : "450", posY : "540" },
{ID: "43", Block: "Block_02", posX : "250", posY : "440" },
{ID: "46", Block: "Block_03", posX : "50", posY : "54" },
{ID: "54", Block: "Block_04", posX : "140", posY : "210" },
{ID: "55", Block: "Block_05", posX : "900", posY : "820" },
{ID: "79", Block: "Block_06", posX : "380", posY : "520" }
]};

And this is the code that I have written to display the contents of the array.

alert ('array length is : ' + divData.items.length);

This statement returns a value of 6 which is correct, Also, I can push data into the array with this statement the alert statement now says 7.

divData.items.push({ID: "266", Block: "Block_01", posX : "450", posY : "540" });

The problem is when I try to display the contents of the array with the following code, nothing happens.

for (var i=0;i<divData.items.length;i++)
{
document.write(divData.items[i] + "<br>");
}       

The output on the screen is this [object Object] seven times.

What am I doing wrong?

Any help will be much appreciated.

Thanks

Chris

1 Answer 1

2

The 'items' in your array are objects. You can't output an object on the screen directly. You have to specify which property of the object you are trying to access:

for (var i = 0;i < divData.items.length; i++)
{
  document.write(divData.items[i].ID + "<br/>"); // access the OBJECT's property!
}   

You may want to do something like:

for (var i = 0;i < divData.items.length; i++)
{
  $("#container").append("<div class='positionedDiv' id='" + divData.items[i].ID + "' style='top: " + divData.items[i].posY + "px;left:" + divData.items[i].posX + "px;></div>");
}   

Some CSS:

.positionedDiv {
  position: absolute; 
}
Sign up to request clarification or add additional context in comments.

3 Comments

Got it. Thanks so much, I just didn't make the obvious connection. Thanks so much.
Just of interest, how would I delete a row?
@Chris: If this answers your question, then make sure to upvote the answer and mark it as accepted. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.