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

如何用jQuery和AJAX实现可编辑<td>的数字输入与长度限制?

实现可编辑表格单元格的数字输入限制(含位数控制)

需求说明

所有可编辑<td>仅允许输入数字,其中product_number字段最多输入2位数字,其余字段(product_count、product_code、product_price)最多输入3位数字。

实现方案

通过实时输入拦截和提交前校验两步实现需求,确保用户输入完全符合规则:

修改后的JavaScript代码

// 给所有可编辑td绑定输入限制事件
$("td[contentEditable='true']").on('keydown input', function(e) {
    const $this = $(this);
    // 根据字段类型设置最大长度
    const maxLength = $this.data('id') === 'product_number' ? 2 : 3;
    const currentValue = $this.text();

    // 拦截非数字按键(允许退格、删除、方向键等控制键)
    const allowedControlKeys = [8, 9, 13, 37, 38, 39, 40, 46];
    if (!allowedControlKeys.includes(e.keyCode) && (e.key < '0' || e.key > '9')) {
        e.preventDefault();
        return;
    }

    // 限制输入长度
    if (currentValue.length >= maxLength && !allowedControlKeys.includes(e.keyCode)) {
        e.preventDefault();
    }

    // 处理粘贴的非数字内容,自动清理并截断
    if (e.type === 'input') {
        const cleanedValue = currentValue.replace(/[^0-9]/g, '').slice(0, maxLength);
        if (cleanedValue !== currentValue) {
            $this.text(cleanedValue);
            // 保持光标在内容末尾
            const range = document.createRange();
            const selection = window.getSelection();
            range.selectNodeContents($this[0]);
            range.collapse(false);
            selection.removeAllRanges();
            selection.addRange(range);
        }
    }
});

// 保存按钮点击事件
$("#btnSaveAction").on("click", function() {
    let params = "";
    let isValid = true;
    let errorMsg = "";

    $("td[contentEditable='true']").each(function() {
        const $this = $(this);
        const fieldId = $this.data('id');
        const value = $this.text().trim();
        const maxLength = fieldId === 'product_number' ? 2 : 3;

        if (value !== "") {
            // 校验是否为纯数字
            if (!/^\d+$/.test(value)) {
                isValid = false;
                errorMsg += `${fieldId.replace('_', ' ')}必须是数字\n`;
                return;
            }
            // 校验长度是否符合要求
            if (value.length > maxLength) {
                isValid = false;
                errorMsg += `${fieldId.replace('_', ' ')}最多输入${maxLength}位数字\n`;
                return;
            }
            // 组装提交参数
            params += params ? "&" : "";
            params += `${fieldId}=${value}`;
        }
    });

    // 校验不通过则提示并阻止提交
    if (!isValid) {
        alert(errorMsg);
        return;
    }

    if (params !== "") {
        $.ajax({
            url: "insert-row.html",
            type: "POST",
            data: params,
            success: function(response) {
                $("#ajax-response").append(response);
                $("td[contentEditable='true']").text("");
            }
        });
    }
});

代码说明

  1. 实时输入拦截:

    • 通过keydown事件拦截非数字输入,仅允许数字和必要的控制键(退格、方向键等)。
    • 根据data-id区分字段,动态设置最大输入长度,超过长度时阻止继续输入。
    • 通过input事件处理粘贴/拖拽的非数字内容,自动清理无效字符并截断到最大长度,同时保持光标在内容末尾。
  2. 提交前校验:

    • 遍历所有可编辑单元格,二次验证内容是否为纯数字、是否符合长度限制。
    • 校验不通过时弹出错误提示,阻止AJAX提交;校验通过后再组装参数发起请求,保持原逻辑的提交流程。

HTML代码(无需修改)

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<div id="add-product">
  <div class="txt-heading">Add Product</div>
  <table cellpadding="10" cellspacing="1">
    <tbody>
      <tr>
        <th><strong>Number</strong></th>
        <th><strong>Count</strong></th>
        <th><strong>Code</strong></th>
        <th style="text-align:right;"><strong>Price</strong></th>
      </tr>
      <tr>
        <td contentEditable="true" data-id="product_number"></td>
        <td contentEditable="true" data-id="product_count"></td>
        <td contentEditable="true" data-id="product_code"></td>
        <td contentEditable="true" data-id="product_price" style="text-align:right;"></td>
      </tr>
    </tbody>
  </table>
  <div id="btnSaveAction">Save to Database</div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 20:54:18