locked
Jquery addition and subtraction problem RRS feed

  • Question

  • User-2059141420 posted

    Hi all,

    I'm creating an input number increment using jQuery but no success yet 

    My code as

    HTML

    <div class="sp-quantity">
    <div class="sp-minus fff"> <a class="ddd" href="#">-</a></div>
    <div class="sp-input">
    <input type="text" value="5">
    </div>
    <div class="sp-plus fff"> <a class="ddd" href="#">+</a></div>
    </div>

    JS

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

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

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

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

    });

    Please help me to fix this problem. Thanks!

    Friday, January 11, 2019 3:56 AM

Answers

  • User-552477072 posted

    You update your code as

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

    var $button = $(this);
    var oldNo = $button.closest('.sp-quantity').find("input").val();

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

    $button.closest('.sp-quantity').find("input").val(newNo);

    });

    Hopefully, it will do for you.

    Please don't forget to mark as answer if it helps you. Thanks!

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 11, 2019 4:02 AM

All replies

  • User-552477072 posted

    You update your code as

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

    var $button = $(this);
    var oldNo = $button.closest('.sp-quantity').find("input").val();

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

    $button.closest('.sp-quantity').find("input").val(newNo);

    });

    Hopefully, it will do for you.

    Please don't forget to mark as answer if it helps you. Thanks!

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 11, 2019 4:02 AM
  • User-2059141420 posted

    Thanks. It is working fine.

    Friday, January 11, 2019 4:05 AM