You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery中增减按钮无法为输入框赋值问题

问题排查与修复:商品数量绑定及购物车提交问题

嘿,我帮你梳理下代码里的几个关键问题,咱们一步步来解决:

核心问题点

  • 数量输入框无初始值:你的输入框默认value='',一开始是空的,点击增减按钮时逻辑上在改值,但视觉上看不到初始数值,而且第一次计算时容易出现非预期问题
  • 购物车提交时选择器不匹配:提交代码里用$row.find('.quantity').val()获取数量,但输入框的class是field,不是quantity,导致根本拿不到数量值
  • 减号按钮逻辑有漏洞:当输入框为空时,$(this).next().val() > 0会把空字符串转成0,虽然不会报错,但逻辑不够严谨

修复后的代码(关键修改已标注)

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<title>Items List</title>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<h1>Welcome to LassiShop </h1>
<c:set var="url" value="/cart"/>
<c:if test="${itemsData.size() gt 0}">
<table class="table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Price</th>
<th scope="col">Quantity</th>
</tr>
</thead>
<tbody>
<c:forEach items="${itemsData}" var="item">
<tr>
<td>
<c:out value="${item.name}"/>
<input type="hidden" class="name" value="${item.name}">
</td>
<td>
<c:out value="${item.price}"/>
<input type="hidden" class="price" value="${item.price}">
</td>
<td>
<input type='button' value='-' class='sub'/>
<!-- 1. 设置初始值为0,同时把class改成quantity,和提交选择器对应 -->
<input type="text" name="quantity" readonly='true' value='0' class='quantity'>
<input type='button' value='+' class='add'/>
</td>
<td><button class="btn btn-primary" type="submit">ADD TO CART</button></td>
</tr>
</c:forEach>
</tbody>
</table>
</c:if>
<c:if test="${itemsData.size() eq 0}">
<h3>No Products available for this Category</h3>
</c:if>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script>
$('.add').click(function () {
    // 先把值转成数字,避免空值问题
    const currentVal = parseInt($(this).prev().val()) || 0;
    $(this).prev().val(currentVal + 1);
});
$('.sub').click(function () {
    const currentVal = parseInt($(this).next().val()) || 0;
    // 确保不会减到负数
    if (currentVal > 0) {
        $(this).next().val(currentVal - 1);
    }
});
$(document).on('click', ".btn", function() {
    var $row = $(this).closest('tr');
    var itemData = {
        name: $row.find('.name').val(),
        price: $row.find('.price').val(),
        // 2. 现在选择器和输入框class匹配,能正确获取数量
        quantity: $row.find('.quantity').val()
    };
    console.log(itemData)
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "/cart",
        data: JSON.stringify(itemData),
        dataType: 'json',
    });
});
</script>
</body>
</html>

额外小建议

  • 可以给数量输入框加个固定宽度,比如style="width: 60px; text-align: center;",让布局更整齐
  • 提交购物车后可以在AJAX的success回调里加个提示,比如alert('商品已加入购物车'),提升用户体验

内容的提问来源于stack exchange,提问作者1up

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 03:57:36