L84
L84

Reputation: 46308

Add Number on Button Click using jQuery?

I have a + and - button. I need to have them increase or decrease an input value based on the click. I have tried the following code:

HTML

<label for="CAT_Custom_410672">Veloce</label>
<input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
 <ul class="button-group button-click">
  <li><a href="#" class="small button secondary"><i class="fa fa-plus"><span class="hide">+</span></i></a></li>
  <li><a href="#" class="small button secondary"><i class="fa fa-minus"><span class="hide">-</span></i></a></li>
 </ul>

JS

$(function() {
$(".button-click").on("click", function() {

  var $button = $(this);
  var oldValue = $button.parent().find("input").val();

  if ($button.text() == "+") {
      var newVal = parseFloat(oldValue) + 1;
    } else {
   // Don't allow decrementing below zero
    if (oldValue > 0) {
      var newVal = parseFloat(oldValue) - 1;
    } else {
      newVal = 0;
    }
  }

  $button.parent().find("input").val(newVal);

})
});

How do I correct the script to function properly?

Note: No errors are thrown. It just doesn't work.

Upvotes: 0

Views: 4347

Answers (2)

elboletaire
elboletaire

Reputation: 5357

The problem is that you are selecting .button-click and that's the class of the parent list

Try this:

$(function() {
$(".button-click a").on("click", function() {

  var $button = $(this);
  var oldValue = $button.closest("ul").prev().val();

  if ($button.text() == "+") {
      var newVal = parseInt(oldValue) +1;
    } else {
   // Don't allow decrementing below zero
    if (oldValue > 0) {
      var newVal = parseInt(oldValue - 1);
    } else {
      newVal = 0;
    }
  }
  $button.closest("ul").prev().val(newVal);
})
});

Working Example

Upvotes: 1

Giancarlo PSK
Giancarlo PSK

Reputation: 231

Try this fiddle

<label for="CAT_Custom_410672">Veloce</label>
 <input type="text" class="cat_textbox" id="CAT_Custom_410672" name="CAT_Custom_410672" maxlength="4000" value="0" />
 <ul class="button-group button-click">
  <li><a href="#" class="small button secondary my_button"><i class="fa fa-plus"><span class="hide">+</span></i></a></li>
<li><a href="#" class="small button secondary my_button"><i class="fa fa-minus"><span class="hide">-</span></i></a></li>
</ul>

$(document).ready(function() {
$(".my_button").on("click", function(event){

  event.preventDefault();

  var $button = $(this);

  var oldValue = $('#CAT_Custom_410672');
  var newVal;
  if ($button.find('.hide').text() == "+") {
       newVal = parseFloat(oldValue.val()) + 1;
    } else {
   // Don't allow decrementing below zero
    if (oldValue.val() > 0) {
      newVal = parseFloat(oldValue.val()) - 1;
    } else {
      newVal = 0;
    }
  }

  oldValue.val(newVal);
 });
});

Upvotes: 1

Related Questions