views:

386

answers:

3

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

+2  A: 

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.

Nick Craver
Thanx, your solution works!
Mircea
+1  A: 
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;
    });
});
Darin Dimitrov
Thanx, your solution also work! Thank you for the support
Mircea
A: 

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

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

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

--SEAN O

Sean O