user759235
user759235

Reputation: 2207

live update a value on change with jquery

I have a span which contains the number of a element(in this case it counts the number of li elements in a list), these list items can be deleted so the number will change, how can i live update the number everytime the list gets changed?

This is the code that i use to count the list items

    var getTotal = jQuery('#ul li').length;
    $(".gettotal").text(getTotal);

I have looked on google but i didn't find anything.

Upvotes: 0

Views: 782

Answers (2)

Jim Rubenstein
Jim Rubenstein

Reputation: 6920

How are your li elements created or deleted? You'll want to trigger a count update on that event. You can utilize jQuery's ability to create/trigger custom events with bind and trigger.

$('#ul').bind('li_deleted', function()
{
    $('.gettotal').text( $('#ul li').length );
});

//and every time an li is deleted..
$('#ul').trigger('li_deleted');

Another (and not so good) option is to run a timer on the page, and check if the # of list elements changes - but that's going to be very resource intensive, i wouldn't do it unless it was a last resort.

Upvotes: 1

ShaneBlake
ShaneBlake

Reputation: 11096

Depending on how often your list length changes, you may want to have a look at the Data-Link plugin for jQuery.

http://api.jquery.com/category/plugins/data-link

Upvotes: 0

Related Questions