使用jQuery单击按钮时添加数字

Add Number on Button Click using jQuery?

本文关键字:添加 数字 按钮 jQuery 单击 使用      更新时间:2023-09-26

我有一个+和-按钮。我需要让他们根据点击增加或减少输入值。我已经尝试了以下代码:

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);
})
});

如何更正脚本以使其正常运行?

注意:不会引发任何错误。它就是不起作用。

问题是您选择的是.button-click,而这是父列表的类

试试这个:

$(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);
})
});

工作示例

试试这个小提琴

<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);
 });
});