通过jQuery在正负输入上添加“this”

Add 'this' on plus-minus inputs via jQuery

本文关键字:添加 this 输入 jQuery 通过      更新时间:2023-09-26
<form id='myform' method='POST' action='#'>
    <input type='button' value='-' class='qtyminus' field='quantity' />
    <input type='text' name='quantity' value='0' class='qty' />
    <input type='button' value='+' class='qtyplus' field='quantity' />
</form>

我在我的引导站点上有一个带有加号和减号功能的输入。它被称为自定义js并且工作正常。

但是如果我在一个页面中有两个输入,一起工作。但是,它必须是分开的。

演示

我该如何解决它?

您可以使用

jquery .siblings并选择一个输入,该输入是按钮的同级。

杰斯菲德尔

jQuery(document).ready(function() {
  // This button will increment the value
  $('.qtyplus').click(function(e) {
    // Stop acting like a button
    e.preventDefault();
    // Get the field name
    fieldName = $(this).attr('field');
    // Get its current value
    var currentVal = parseInt($(this).siblings('input[name=' + fieldName + ']').val());
    // If is not undefined
    if (!isNaN(currentVal)) {
      // Increment
      $(this).siblings('input[name=' + fieldName + ']').val(currentVal + 1);
    } else {
      // Otherwise put a 0 there
      $(this).siblings('input[name=' + fieldName + ']').val(0);
    }
  });
  // This button will decrement the value till 0
  $(".qtyminus").click(function(e) {
    // Stop acting like a button
    e.preventDefault();
    // Get the field name
    fieldName = $(this).attr('field');
    // Get its current value
    var currentVal = parseInt($(this).siblings('input[name=' + fieldName + ']').val());
    // If it isn't undefined or its greater than 0
    if (!isNaN(currentVal) && currentVal > 0) {
      // Decrement one
      $(this).siblings('input[name=' + fieldName + ']').val(currentVal - 1);
    } else {
      // Otherwise put a 0 there
      $(this).siblings('input[name=' + fieldName + ']').val(0);
    }
  });
});
#myform {
  text-align: center;
  padding: 5px;
  border: 1px dotted #ccc;
  margin: 2%;
}
.qty {
  width: 40px;
  height: 25px;
  text-align: center;
}
input.qtyplus {
  width: 25px;
  height: 25px;
}
input.qtyminus {
  width: 25px;
  height: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id='myform' method='POST' action='#'>
  <input type='button' value='-' class='qtyminus' field='quantity' />
  <input type='text' name='quantity' value='0' class='qty' />
  <input type='button' value='+' class='qtyplus' field='quantity' />
</form>
<form id='myform2' method='POST' action='#'>
  <input type='button' value='-' class='qtyminus' field='quantity' />
  <input type='text' name='quantity' value='0' class='qty' />
  <input type='button' value='+' class='qtyplus' field='quantity' />
</form>