JQuery incrementing id and var on click

I am trying to make a button that increases when I click on its identifier and variable. I was able to find some code in StackOverflow that increases the value of the input field, but I don't know how to change it.

Here is the markup:

<input type="text" name="qty" value="0" /> <p id="inc">Increase</p> <p id="dec">Decrease</p> 

And jQuery

 <script> $(document).ready(function() { $(function() { $("#inc").click(function() { $(":text[name='qty']").val(Number($(":text[name='qty']").val()) + 1); $('#inc').addClass (Number + 1); // this one does not work var incrementVar = (Number + 1); // this one also does not work }); $("#dec").click(function() { $(":text[name='qty']").val(Number($(":text[name='qty']").val()) - 1); }); }); }); </script> 

This increases the value of val in the input, but I cannot get it to increment the class $ ('# inc') and var incrementVar.

What should I do? Thanks you

+4
source share
3 answers
 var incrementVar = 0; $(function() { $("#inc").click(function() { var value = parseInt($(":text[name='qty']").val()) + 1; $(":text[name='qty']").val(value); $('#inc').addClass('a' + value); // I believe class names cannot start with a number incrementVar = incrementVar + value; }); }); 
+3
source

Class names cannot begin with a number; see this discussion for details . If you prefix your class, say .c1 , .c2 , etc ... you can do something like this:

 $(function() { $("#inc").click(function() { var num = $(":text[name='qty']").val(function(i, v) { return Number(v) + 1; }).val(); $(this).addClass ('c' + num); var incrementVar = num; }); $("#dec").click(function() { $(":text[name='qty']").val(function(i, v) { return Number(v) - 1; }); }); }); 

One more note: there is no need for $(document).ready(function() { and $(function() { , they are equivalent, wrapping in one is just fine.

+5
source

For additional keyboard support (up / down arrows for adding / subtracting) for this input, my Increment plugin may come in handy: http://sean-o.com/increment

Just download and include the script, then call with a single line of code:

 $(":text[name='qty']").increment({ increment: 1 }); 

- SEAN O

0
source

Source: https://habr.com/ru/post/1303694/


All Articles