The number of increments 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 an integer of 1.

I want to increase it by 1 when I click like:

 $('.next').click(function() 

How can i do this?

+4
source share
4 answers

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 .

+4
source

Somewhat inspired by the original version of Tomalak's answer, you can use the callback-based .text version to change the value in a single jQuery call:

 $ticket.text(function(i, t) { return parseInt(t, 10) + 1; }); 

For those of you who tried to use ++ , it will not work for two reasons:

  • You can use ++ only for variables, not for the return value of a function
  • Even then, in postfix mode, it would return the old value, not the added value
+1
source
 $ticket.click(function(e) { $(this).val(parseInt($(this).val()) + 1); e.preventDefault(); }); 
0
source

try it

  $ticket.val($ticket.val()+1) 

EDIT

 $ticket.text(parseInt($ticket.text(),10)+1); 

If the item is somewhere other than the form

Sorry for the error, ++ does not work here. Respectively edited the solution.

-1
source

All Articles