tags:

views:

53

answers:

5

Hello,

I've got a small dilemma, that should hopefully be easy to resolve.

I am loading some data using jQuery/JSON/PHP-- essentially, the data being loaded are several <li> elements.

The following code works correctly:

function load_list() {
$.getJSON('json/load.php', function(data) {
            $.each(data, function(k, v){                                 
            $("#my_div").append('
                                         <li> \
                                          <div> \
                                           <input type="checkbox"> \
                                          </div> \
                                          <div>'+v.due_date+'</div> \
                                          <h3> \
                                           <span>'+v.title+'</span> \
                                           </h3> \
                                          </li> \
                                                  ');
                                        });
});
}

However, let's say I want to update "#my_div" and call the function again later on, say, every 20 seconds. If I re-call the function above, it actually appends the items again, thus duplicating the results.

My question is (forgive me for not knowing): How can I rewrite the function above to load all events and refresh it and set the HTML of the "#my_div" to be brand new and not to not duplicate?

Thanks very much.

A: 

You can call the html function to set an element's HTML content, like this:

        $("#my_div").html('
                                     <li> \
                                      <div> \
                                       <input type="checkbox"> \
                                      </div> \
                                      <div>'+v.due_date+'</div> \
                                      <h3> \
                                       <span>'+v.title+'</span> \
                                       </h3> \
                                      </li> \
                                              ');
SLaks
A: 

Use html instead append

antyrat
+3  A: 

Call $("#my_div").empty() at the beginning of the anonymous function containing the .each() call.

Ignacio Vazquez-Abrams
+1 - All the other answers are forgetting the fact this is in a loop :)
Nick Craver
Hi Ignacio, thanks for the reply. This certainly did the trick. I can accept this as the "correct" answer in 7 minutes (according to SO).
Dodinas
A: 

Use the html('<li>...') tag -- it replaces content rather than appends it.

Kerry
A: 

Dodinas, you'd want to use the following:

$("#my_div").html('<li>...</li>');

using the html() method inserts the html.

TheCloudlessSky