creating dynamic list with jquery
dynamic, jquery
Solution
You don't really need to use an event. When you get the updated list, call the update method directly.
However, as other users have indicated, using a data-binding library might be better.
start_with.html
<div id="users">
<ul class="list">
<li>
<h3 class="name">name1</h3>
</li>
<li>
<h3 class="name">name2</h3>
</li>
</ul>
</div>
update_list.js
// Note: This method will clear any user selections and may cause other problems since the previous list is deleted and recreated.
function update_list(updated_users) {
// clear the existing list
$('#users .list li').remove();
$.each(updatedUsers, function(index,userName) {
$('#users .list').append('<li><h3 class="name">'+userName+'</h3></li>')
});
}
example_1.js
// Get the updated list
var updated_users = ["name1", "name2", "name3"];
// Update it
update_list(updated_users);
after_example_1.html
<div id="users">
<ul class="list">
<li><h3 class="name">name1</h3></li>
<li><h3 class="name">name2</h3></li>
<li><h3 class="name">name3</h3></li>
</ul>
</div>
example_2.js
// Example by AJAX get using a made-up URL
$.get('http://api.example.com/users/active.json', function(data) {
// What you do with data depends on what the API returns...
// I'm assuming it returns an array of users.
// data = ['user1', 'user2', 'user3'];
update_list(data);
})
after_example_2.html
<div id="users">
<ul class="list">
<li><h3 class="name">user1</h3></li>
<li><h3 class="name">user2</h3></li>
<li><h3 class="name">user3</h3></li>
</ul>
</div>
Note: One drawback to this method is that the old list gets destroyed. This means that if your list has input boxes, for example, their user-entered content would be destroyed on update. If you have state in your list, you'll have to use a different method to update the list if you also want to preserve the state of elements.
Problem
let me start by saying that i saw similar questions on forum, however i didn't find one which i managed to understand and apply to my situation. Having said that, my question is as follows: I want to build a list which dynamically changes. ( the list shows the names of useres who are currently logged in). Let's say that the names of the logged in users are stored in an array = ["name1", "name2", "name3" ....] and that the data in the array is the updated data. the form is: ``` <div id="users"> <ul class="list"> <li> <h3 class="name">name1</h3> </li> <li> <h3 class="name">name2</h3> </li> </ul> </div> ``` how can i modify the list, using jquery, to display the names form the array and dynamically change by it's content? many thanks.