如何使用 jQuery 增加数量字段的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1211354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:55:29  来源:igfitidea点击:

How to increase the value of a quantity field with jQuery?

jquery

提问by JonoW

I have a form with some quantity field and a plus and minus sign on each side,

我有一个表格,上面有一些数量字段,每边都有一个加号和减号,

    <form id="myform">
        product1
        <input type="submit" value="+" id="add">
        <input type="text" id="qty1">
        <input type="submit value="-" id="minus">
        product2
        <input type="submit" value="+" id="add">
        <input type="text" id="qty2">
        <input type="submit value="-" id="minus">
    </form>

I'd like to increase the value of the field by one if the add button is pressed and decrease by one if minus is pressed. Also the value shouldn't get less than 0.

如果按下添加按钮,我想将字段的值增加一,如果按下减号则减少一。此外,该值不应小于 0。

Is there a way to do this in jQuery?

有没有办法在 jQuery 中做到这一点?

回答by Domenic

First of all, type="submit"should be type="button"in all cases. Also, you cannot have two elements with the same ID; I assume you want add1, minus1, add2, minus2, etc.

首先,type="submit"应该type="button"在所有情况下。此外,不能有两个具有相同 ID 的元素;我假设你想add1minus1add2minus2,等。

The following jQuery code should work great.

下面的 jQuery 代码应该很好用。

$(function () {
    var numButtons = 10;
    for (var i = 1; i <= numButtons; ++i) {
        $("#add" + i).click(function () {
            var currentVal = parseInt($("#qty" + i).val());
            if (!isNaN(currentVal)) {
                $("#qty" + i).val(currentVal + 1);
            }
        });

        $("#minus" + i).click(function () {
            var currentVal = parseInt($("qty" + i).val());
            if (!isNaN(currentVal) && currentVal > 0) {
                $("#qty" + i).val(currentVal - 1);
            }
        });
    }
});

Worth noting:

值得注意:

  • I wrap everything in a $(function() { ... })call so that you attach the event handlers only after the page loads. (Specifically, after the DomContentLoadedevent.) This prevents errors about how an object with the ID "add1" doesn't exist or whatever, because technically that object doesn't exist until the page actually loads.
  • Checks for NaNhandles the case of the user typing non-numeric stuff into the field. You could add your own logic for that in particular, e.g. auto-convert non-numeric properties to 0 whenever someone clicks add or minus.
  • 我将所有内容都封装在一个$(function() { ... })调用中,以便您仅在页面加载后附加事件处理程序。(特别是在DomContentLoaded事件之后。)这可以防止关于 ID 为“add1”的对象如何不存在等错误,因为从技术上讲,该对象在页面实际加载之前不存在。
  • 检查NaN处理用户在字段中输入非数字内容的情况。您可以为此添加自己的逻辑,例如,每当有人单击加号或减号时,将非数字属性自动转换为 0。

回答by danh

I'm a rookie, but I did it like this for integers...

我是菜鸟,但我对整数是这样做的......

<div class="quantityInput" min="-32" max="32">
    <input type="text" class="quantityText">
    <input type="button" value="+" class="quantityPlus">
    <input type="button" value="-" class="quantityMinus">
</div>

min and max attributes are optional. Then, inside jQuery(document).ready(...

min 和 max 属性是可选的。然后,在 jQuery(document).ready(...

$(".quantityMinus").live("click", function() {
  var qInput = $(this).parents(".quantityInput");
  var qText = qInput.find(".quantityText");
  var qValue = parseInt((qText.val())? qText.val() : 0);
  qText.val(Math.max(qValue - 1, (qInput.attr("min"))? qInput.attr("min") : -0xffff));
});

$(".quantityPlus").live("click", function() {
  var qInput = $(this).parents(".quantityInput");
  var qText = qInput.find(".quantityText");
  var qValue = parseInt((qText.val())? qText.val() : 0);
  qText.val(Math.min(qValue + 1, (qInput.attr("max"))? qInput.attr("max") : 0xffff));
});

回答by JonoW

Your html isn't quite valid, you have multiple elements with the same id, it should be unique. But lets say you only had one set of inputs/buttons:

您的 html 不太有效,您有多个具有相同 id 的元素,它应该是唯一的。但是假设您只有一组输入/按钮:

$("#add").click(function(){
  var newQty = +($("#qty1").val()) + 1;
  $("#qty1").val(newQty);
});

$("#minus").click(function(){
  var newQty = +($("#qty1").val()) - 1;
  if(newQty < 0)newQty = 0;
  $("#qty1").val(newQty);
});

回答by Zed

You should use unique id'sfor all your inputs, e.g. qty1_add, qty1_minus. Then you can attach the click event to these buttons:

您应该为所有输入使用唯一 ID,例如qty1_add, qty1_minus。然后你可以将点击事件附加到这些按钮上:

$("#qty1_add").click( function() {
   $("#qty1").val( parseInt($("#qty1").val()) + 1);
}).

回答by moctebain

This is the improved response of the first aswer:

这是第一个答案的改进响应:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function()
{
    $(".add").click(function()
    {
        var currentVal = parseInt($(this).next(".qty").val());
        if (currentVal != NaN)
        {
            $(this).next(".qty").val(currentVal + 1);
        } 
    });

    $(".minus").click(function()
    {
        var currentVal = parseInt($(this).prev(".qty").val());
        if (currentVal != NaN)
        {
            $(this).prev(".qty").val(currentVal - 1);
        }
    });
});

</script>
</head>

<body>
    <form id="myform">
        product1
        <input type="button" value="+" id="add1" class="add" />        
        <input type="text" id="qty1" value="-1" class="qty" />        
        <input type="button" value="-" id="minus1" class="minus" /><br /><br />

        product2
        <input type="button" value="+" id="add2" class="add" />        
        <input type="text" id="qty2" value="-10" class="qty" />        
        <input type="button" value="-" id="minus2" class="minus" />

    </form>

</body>

I hope they serve.... :D

我希望他们服务.... :D

回答by Harry Lincoln

Thanks so much for everyone who got involved. All I drew upon and was able to come up with this in the end, that served the site very well (it was just the css that was a pain!)

非常感谢所有参与的人。所有我借鉴并最终能够想出这个,这很好地为网站服务(只是 css 很痛苦!)

HTML:

HTML:

<div id="qtybox"><label for="qty">
<venda_text id=site.quantity>
</label><input name="qty" id="qty" type="text" value="1" size="3" maxlength="2"></input>
<button id="qtyplus" onclick="return false"></button>
    <button id="qtyminus" onclick="return false"></button>

</div>

js:

js:

jQuery(function(){
    jQuery("#qtyplus").click(function(){     
     jQuery(":text[name='qty']").val( Number(jQuery(":text[name='qty']").val()) + 1 );
    });
    jQuery("#qtyminus").click(function(){
     if(jQuery('#qty').val()>1)
      jQuery(":text[name='qty']").val( Number(jQuery(":text[name='qty']").val()) - 1 );

    });
  });

CSS:

CSS:

#qtybox button#qtyplus {
    background: url("../images/social_icons/elements.png") no-repeat scroll -268px -223px   
    transparent;
    border: medium none;
    cursor: pointer;
    display: block;
    float: right;
    height: 23px;
    width: 23px;
}

As you can see, I removed the values of the +'s and -'s - hated how it was rendered!

如您所见,我删除了 + 和 - 的值 - 讨厌它的呈现方式!

回答by usoban

First, at minus buttons, you need to have type="submit", not type="submit, but I assume that is typing mistake ;)

首先,在减号按钮上,您需要输入 type="submit",而不是 type="submit,但我认为这是输入错误;)

If you want to do that, you should change plus and minus button ids to something like 'minus-qty1', 'add-qty1', etc. to identify which input you'd like to update.

如果您想这样做,您应该将加号和减号按钮 ID 更改为“minus-qty1”、“add-qty1”等,以标识您要更新的输入。

  <form id="myform">
    product1
    <input type="button" value="+" id="add-qty1" onclick="increase(this)">
    <input type="text" id="qty1">
    <input type="button" value="-" id="minus-qty1" onclick="decrease(this)">
    product2
    <input type="button" value="+" id="add-qty2" onclick="increase(this)">
    <input type="text" id="qty2">
    <input type="button" value="-" id="minus-qty2" onclick="decrease(this)">

  </form>

function increase(button)
{
 var id = $(button).attr('id');
 var fname = id.substr(3);

 var newval = parseInt($("#"+fname).val()) + 1;
 $("#" + fname).val(newval);
}


function decrease(button)
{
 var id = $(button).attr('id');
 var fname = id.substr(5);

 var newval = parseInt($("#"+fname).val()) - 1;
 $("#" + fname).val(newval);
}

I hope it works, I didn't try it :)

我希望它有效,我没有尝试过:)

回答by Matt Sach

I think this should do it:

我认为应该这样做:

$('#add').click(function (e) {
    var quant = $(this).next('input');
    quant.val(parseInt(quant.val(), 10) + 1);
};
$('#minus').click(function (e) {
    var quant = $(this).prev('input');
    quant.val(parseInt(quant.val(), 10) - 1);
    if (parseInt(quant.val(), 10) < 0)
    { quant.val(0); }
};

This does however depend on the relative positioning of the controls not changing.

然而,这取决于控件的相对位置不变。