2

I'm trying to set up a refresh on div after an object array has received the necessary inputs and has been submitted for displaying. So far I've done this:

  var users = [
    {name: "John Smith", description: "Some chap", image: "None"},
    {name: "Elizabeth II", description: "A fancy lass", image: "None"}
  ];

  function arrayAdd() {
    var title_text = $("#title_text").val();
    var description_text = $("#description_text").val();
    var image_text = $("#image_text").val();

    users.push({name:title_text,description:description_text,image:image_text});
    console.log(users);

    for (var i = 0; i <= users.length; i++) {
      $("#users").html(users[i]['name']);
    };
  }

But that only shows the last value added, can you please show me a way to mend this?

3 Answers 3

3

Your current code is over-writing the entire HTML of the element on each iteration so only the last one is visible. Change this:

$("#users").html(users[i]['name']);

To:

$("#users").append(users[i]['name']);
Sign up to request clarification or add additional context in comments.

Comments

2

Try this, in the for loop you are using html, it replaces everything inside that element use .append() instead

$('#users').append(users[i]['name']);

Comments

0

Change html to append. You're clearing the HTML on each iteration.

$("#users").empty();

for (var i = 0; i <= users.length; i++) {
  $("#users").append(users[i]['name']);
};

Comments

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.