RCB
RCB

Reputation: 99

+/- buttons to increment/decrement value with a maximum

I am using the following code to create buttons with a + and a - sign to increment or decrement values. It is working fine, however I need to set a limit that it will not let you increment any more if the total value of the numbers is equal to 5.

HTML:

<div id="page-wrap">

        <h1>Input Number Incrementer</h1>

      <form method="post" action="">
      <div class="numbers-row">
        <label for="name">French Hens</label>
        <input type="text" name="french-hens" id="french-hens" value="0">
      </div>
      <div class="numbers-row">
        <label for="name">Turtle Doves</label>
        <input type="text" name="turtle-doves" id="turtle-doves" value="0">
      </div>
      <div class="numbers-row">
        <label for="name">Partridges</label>
        <input type="text" name="partridge" id="partridge" value="0">
      </div>
      <div class="buttons">
        <input type="submit" value="Submit" id="submit">
      </div>
    </form>

    </div>

Jquery:

$(function() {

  $(".numbers-row").append('<div class="inc button">+</div><div class="dec button">-</div>');

  $(".button").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);

  });

});

Upvotes: 0

Views: 4180

Answers (2)

Anujith
Anujith

Reputation: 9370

See this: DEMO

$(function () {

 $(".numbers-row").append('<div class="inc button">+</div><div class="dec button">-</div>');

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

    var $button = $(this);
    var oldValue = $button.parent().find("input").val();
    var sum = 0;
    $('.numbers-row input[type="text"]').each(function () {
        sum += Number($(this).val());
    });
    if ($button.text() == "+" && sum < 5) {
        var newVal = parseFloat(oldValue) + 1;
    } else if ($button.text() == "-") {
        // Don't allow decrementing below zero
        if (oldValue > 0) {
            var newVal = parseFloat(oldValue) - 1;
        } else {
            newVal = 0;
        }
    } else {
        return false;
    }

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

Upvotes: 1

Cameron
Cameron

Reputation: 572

In this section add the following:

if ($button.text() == "+") {

    if (parseFloat(oldValue) <= 5) {
        var newVal = parseFloat(oldValue) + 1;
    }
}

Upvotes: 0

Related Questions