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
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.
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;
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With