Reputation: 2651
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.
Upvotes: 12
Views: 23215
Reputation: 4508
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));
}
}
Upvotes: 19
Reputation: 10453
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.
Upvotes: 3
Reputation: 591
HTML:
There are <span class="numitems">5</span> items.
JS:
var span = $("span.numitems");
span.html(parseInt(span.html()) - 1);
Upvotes: 7
Reputation:
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());
Upvotes: 1