Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How do I get the contents of a span, subtract by 1, and replace contents of span with new number?

Tags:

jquery

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.

like image 983
dallen Avatar asked Jul 24 '09 22:07

dallen


2 Answers

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));
    }
}
like image 102
drs9222 Avatar answered Sep 23 '22 18:09

drs9222


HTML:

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

JS:

var span = $("span.numitems");
span.html(parseInt(span.html()) - 1);
like image 27
edsoverflow Avatar answered Sep 20 '22 18:09

edsoverflow