tags:

views:

2993

answers:

4

Let's say I have a PHP loop that displays data that you can delete. I'm using AJAX, so when you delete a row, it processes a PHP script and the row disappears from the page.

However, I have something that says "There are 5 items". I'd like that "5" to change when an item is deleted. I figured the easiest way would be to subtract by one in Javascript.

Problem is, I really don't know how. If someone could point me in the right direction, that would be great.

A: 

Update the complete list if there has something changed. Check it using AJAX about every 5 seconds.

Or

There are <span id="number">5</span> items.

and then change the value of span with id 'number' with the current number of rows after deletion. Stack Overflow uses this method when a new answer is posted when you are adding a new one.

You can substract using

parseInt($("span").html());
Time Machine
+4  A: 

HTML:

There are <span class="numitems">5</span> items.

JS:

var span = $("span.numitems");
span.html(parseInt(span.html()) - 1);
edsoverflow
+7  A: 

Assuming the count is in a span with id 'cnt':

$("#cnt").text($("#cnt").text()-1)

Edit:
Safer Version:

var cntTag = $("#cnt:first");
if (cntTag.Length == 1)
{
    var cnt = parseInt(cntTag.text());
    if (!isNaN(cnt))
    {
        cnt--;
        cntTag.text(String(cnt));
    }
}
drs9222
Thanks a million! I'd rather do this than an AJAX "refresh" since this is less stress on the server. The server I'm working on is pretty old and can barely handle the few AJAX requests I already have.
dallen
I can see this coming in handy in the near future +1
jasondavis
Would that be safer with a parseInt() in it? Javascript is pretty forgiving about that sort of thing, but it seems like it might be handy just in case...
Gabriel Hurley
+1  A: 

Let's say we start with three:

<p>There are <span id='number'>3</span> items.</p>
<ol id ='thelist'>
  <li> one
  <li> two 
  <li> three
</ol>

Now we need some jQuery to handle the change event on the list

$(function(){
  $('#thelist').bind('change', function(){
    $('#number').html($('#thelist li').length)
  }
}

every time #thelist changes, it will update the length in #number. One advantage to this approach is that by binding the change event, you don't need to setInterval on a timer or anything like that. Everything just does what its supposed to.

ScottSEA
Very impressive... I'll see if I can rework my list into this format. Thanks!
dallen