首页 > 解决方案 > 增加,减少输入中的值并且不显示负数

问题描述

我正在尝试制作输入表单,它的值可以通过单击 +1 / -1 按钮来增加和减少,我也有 +5 / -5 按钮。

当值为 3 并单击 -5 按钮时,值变为 -2。但我不想显示负数。我希望最小数字始终为“0”。甚至结果值也是负数。

如何修复代码?

$(function() {
  $(".plus").click(function(e) {
    e.preventDefault();
    var $this = $(this);
    var $input = $this.siblings('input');
    var value = parseInt($input.val());

    if (value < 30) {
      value = value + 1;
    } else {
      value = 30;
    }

    $input.val(value);
  });


  $(".plus2").click(function(e) {
    e.preventDefault();
    var $this = $(this);
    var $input = $this.siblings('input');
    var value = parseInt($input.val());

    if (value < 30) {
      value = value + 5;
    } else {
      value = 30;
    }

    $input.val(value);
  });


  $(".minus").click(function(e) {
    e.preventDefault();
    var $this = $(this);
    var $input = $this.siblings('input');
    var value = parseInt($input.val());

    if (value > 0) {
      value = value - 1;
    } else {
      value = 0;
    }

    $input.val(value);
  });


  $(".minus2").click(function(e) {
    e.preventDefault();
    var $this = $(this);
    var $input = $this.siblings('input');
    var value = parseInt($input.val());

    if (value > 0) {
      value = value - 5;
    } else {
      value = 0;
    }

    $input.val(value);
  });


});
.change_qty {
  display: inline-block;
  color: #fff;
  background: #2e748e;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  font-weight: 900;
  line-height: 22px;
}

.cursor_hover {
  cursor: hand;
  cursor: pointer;
}

.change_qty {
  display: inline-block;
  color: #fff;
  background: #2e748e;
  width: 22px;
  height: 22px;
  border-radius: 50%;
  font-weight: 900;
  line-height: 22px;
}

.cursor_hover {
  cursor: hand;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="margin-bottom:2em;text-align:center;">

  <div class="change_qty minus2 cursor_hover">&#45;5</div>
  <div class="change_qty minus cursor_hover">&#45;1</div>

  <input type="numeric" style="height:22px;width:40px;margin:0 .5em;text-align:center;" value="0">

  <div class="change_qty plus cursor_hover">&#43;1</div>
  <div class="change_qty plus2 cursor_hover">&#43;5</div>

</div>

这就是我在这里尝试的 http://jsfiddle.net/a5ktensk/63/

标签: jquery

解决方案


只需更改 if 语句就可以了。

http://jsfiddle.net/a5ktensk/68/

if (value > 5) { 
    value = value - 5; 
} 
else { 
    value = 0; 
}

另一种选择是。

value = value -5;
if(value < 0) {
    value = 0;
}

推荐阅读