Reputation: 35349
Using jQuery, I would like to extract a number from a <span>
and use it to calculate a new value.
<div class="post-100" data-postid="100">
<span class="score">3</span>
</div>
I've got the general Idea, but I can't figure out how to reference the existing span value:
if (response.newvoteid == null)
{
$(".post-" + $(this).data("postid") + " .score").text(
parseInt( **EXISTING VALUE + 1 OR -1**));
}
Update: I am now using the following which fails to calculate the new value, but simply adds a number to the text. For example, <span class="score">3</span>
becomes <span class="score">31</span>
var number = $(".post-" + $(this).data("postId") + " .score").text();
$(".post-" + $(this).data("postId") + " .score").text(number + 1);
Upvotes: 5
Views: 13940
Reputation: 16038
parseInt() is a helper method which requires the string to be parsed as an argument like this:
parseInt($(".score").text())
To do a calculation you can now add your number to the result of parseInt():
var newVal = parseInt($(".score").text()) + 1
its not clear to me, how you want to select the span. Can you explain this a bit clearer?
The above code selects the content of the span via its class for example.
Upvotes: 8
Reputation: 322562
Just pass a function to .text()
that returns the old value incremented (or decremented):
$(".post-" + $(this).data("postid") + " .score").text( function( i, txt ) {
return ( parseInt( txt, 10 ) + 1 ); // Returns the old value,
}); // plus (or minus) 1.
Upvotes: 4
Reputation: 15754
$(spanId).text();
would get the value/text within the span tag.
so something like:
var number = $(spanId).text();
will get you the value, then you can check if its a valid number and parse as you like.
var intRegex = /^\d+$/;
var number = $(spanId).text();
if(intRegex.test(number)) {
...//proceed cuz it's a number
}
Upvotes: -1
Reputation: 15835
<span class="score">3</span>
you have a class name already defined, so using class name you can get the text inside it as below
$(.score).text();
api here
the above code gets you 3
Upvotes: 0