Reputation: 21396
I am using JavaScript with jQuery. I have the following
var $ticket = $nxt.parent().prev().children('.ticket');
and $ticket.text()
is integer 1.
I want to increment it by 1 when when I click as;
$('.next').click(function()
How can I do this??
Upvotes: 3
Views: 369
Reputation: 339816
Somewhat inspired by the original version of Tomalak's answer, you can use the callback-based version of .text
to change the value in a single jQuery call:
$ticket.text(function(i, t) {
return parseInt(t, 10) + 1;
});
For those of you that tried to use ++
, it won't work for two reasons:
++
on variables, not the return value of a functionUpvotes: 1
Reputation: 338228
A fancy solution would be
$.fn.extend({
increment: function () {
return this.text( function (i, currentText) {
return parseInt(currentText, 10) + 1;
});
}
});
In your case use as:
$nxt.parent().prev().children('.ticket').increment();
Also see this jsFiddle.
Upvotes: 4
Reputation: 6867
Try this
$ticket.val($ticket.val()+1)
EDIT
$ticket.text(parseInt($ticket.text(),10)+1);
If the element is somwhere other than a form
Sorry for the mistake, ++
doesnt work here. Have edited the solution accordingly.
Upvotes: -1
Reputation: 9361
$ticket.click(function(e) {
$(this).val(parseInt($(this).val()) + 1);
e.preventDefault();
});
Upvotes: 0