Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery incrementing an ID and var on click

I am trying to do a button that increments on click his ID and a variable. i was able to find some code on StackOverflow that increases the value of an input field but I do not know to change it from there.

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 does increase the val in the input but I can not make it to increment the $('#inc') class and the var incrementVar.

What should I do? Thank you

like image 477
Mircea Avatar asked Mar 10 '10 17:03

Mircea


2 Answers

Class names cannot start 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: no need for $(document).ready(function() { and $(function() { these are equivalent, wrapping in either one alone is fine.

like image 120
Nick Craver Avatar answered Oct 03 '22 05:10

Nick Craver


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;
    });
});
like image 30
Darin Dimitrov Avatar answered Oct 03 '22 05:10

Darin Dimitrov