Alfred
Alfred

Reputation: 21396

Increment number in a cell - JavaScript - jQuery

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

Answers (4)

Alnitak
Alnitak

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:

  1. You can only use ++ on variables, not the return value of a function
  2. Even then, in postfix mode it would have returned the old value, not the incremented value

Upvotes: 1

Tomalak
Tomalak

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

Balanivash
Balanivash

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

Brian Scott
Brian Scott

Reputation: 9361

$ticket.click(function(e) { 
    $(this).val(parseInt($(this).val()) + 1); 
    e.preventDefault(); 
});

Upvotes: 0

Related Questions