如何使用jQuery增加数量字段的值? [英] How to increase the value of a quantity field with jQuery?

查看:129
本文介绍了如何使用jQuery增加数量字段的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

如果要添加,我想将该字段的值增加一 按下按钮,如果按下减号,则减一. 而且该值不应小于0.

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.

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

Is there a way to do this in jQuery?

推荐答案

首先,在所有情况下,type="submit"应该为type="button".同样,您不能有两个具有相同ID的元素.我假设您想要add1minus1add2minus2等.

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.

以下jQuery代码应该很好用.

The following jQuery code should work great.

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

值得注意的是:

  • 我将所有内容包装在$(function() { ... })调用中,以便仅在页面加载后才附加事件处理程序. (特别是在DomContentLoaded事件之后.)这可以防止有关ID为"add1"的对象如何不存在或其他原因的错误,因为从技术上讲,该对象直到页面实际加载时才存在.
  • 检查NaN处理用户在字段中键入非数字内容的情况.您可以为此添加自己的逻辑,例如每当有人单击加号或减号时,会将非数字属性自动转换为0.
  • I wrap everything in a $(function() { ... }) call so that you attach the event handlers only after the page loads. (Specifically, after the DomContentLoaded event.) 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 NaN handles 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.

这篇关于如何使用jQuery增加数量字段的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆