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

HTML表格列重复值与零值校验jQuery脚本优化问询

优化后完整JS代码

// 数字列校验逻辑,支持动态新增行
$('#zonaTable').on('blur', '[name="zona_szam[]"]', function () {
  const $currentInput = $(this);
  const inputVal = $currentInput.val().trim();
  const $error = $('#error');
  // 先隐藏历史错误提示
  $error.hide();

  // 校验1:值不能为0或空
  if (inputVal === '' || Number(inputVal) === 0) {
    $error.html(`<span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span> 
                <strong>ERROR! </strong>输入值不能为0或空`).show();
    $currentInput.val('');
    return;
  }

  // 校验2:值不能重复
  let isDuplicate = false;
  $('[name="zona_szam[]"]').not($currentInput).each(function () {
    if ($(this).val().trim() === inputVal) {
      isDuplicate = true;
      return false; // 匹配到重复直接终止遍历
    }
  });

  if (isDuplicate) {
    $error.html(`<span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span> 
                <strong>ERROR! </strong>数字必须唯一`).show();
    $currentInput.val('');
  }
});

// 表格新增行逻辑
$('#add-row').click(function () {
  const numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
  if (isNaN(numNewRows) || numNewRows <= 0) {
    alert('请输入要添加的行数');
    return;
  }
  const $tbody = $('#zonaTable tbody');
  const $lastRow = $tbody.find('tr:last');
  // 新增行默认清空输入值,避免自带重复值
  const newRowHtml = $lastRow.clone().find('input').val('').end().prop('outerHTML');
  $tbody.append(new Array(numNewRows + 1).join(newRowHtml));
});

优化点说明

  • 事件绑定改用事件委托挂载到固定的表格容器上,监听blur失焦事件,所有动态新增的行的输入框无需额外绑定即可自动触发校验,满足失焦触发的需求
  • 彻底解决清空值误删问题:直接操作当前触发校验的输入框对象,不需要通过ID查找元素,完全规避重复ID导致的操作偏差
  • 新增非零校验逻辑:优先判断输入值是否为空或为0,不符合要求直接提示错误并清空当前输入框
  • 优化重复校验效率:匹配到重复值后立即终止遍历,减少不必要的性能消耗,且只会清空当前输入的重复值,不会影响已有的合法输入
  • 优化新增行逻辑:新增行时自动清空输入框默认值,避免新增行就自带重复值的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 12:06:06