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

表单提交serialize序列化时如何过滤不可见元素仅提交可见填写项

实现方案

核心逻辑是手动筛选需要序列化的表单元素,排除父级隐藏的普通输入项,同时保留你主动设置的type="hidden"全局参数。

修改后的JS逻辑

你只需要替换原来的按钮点击事件代码即可:

$(document).ready(function(){
  $("button").click(function(){
    // 筛选符合要求的表单元素
    const validFields = $('#myform').find('input, select, textarea').filter(function() {
      // 过滤规则:
      // 1. 未禁用
      // 2. 有name属性
      // 3. 要么是主动设置的type=hidden隐藏域,要么是可见元素
      return !this.disabled && this.name 
        && (this.type === 'hidden' || $(this).is(':visible'));
    });
    // 序列化筛选后的字段
    $('#content').text(validFields.serialize());
  });
});

完整可运行代码

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    const validFields = $('#myform').find('input, select, textarea').filter(function() {
      return !this.disabled && this.name 
        && (this.type === 'hidden' || $(this).is(':visible'));
    });
    $('#content').text(validFields.serialize());
  });
});
</script>
</head>
<body>

<form action="" id="myform">
  First name: <input type="text" name="FirstName" value="Mickey"><br>
  Last name: <input type="text" name="LastName" value="Mouse"><br>
  <div style="display:none;"><input type="text" name="isthishidden" value="maybe"></div>
 <input type="hidden" name="action" value="verwerk">
</form>
<button>Serialize form values</button>
<p></p>
<div id="content"></div>

</body>
</html>

效果说明

运行后点击按钮,输出的序列化结果为FirstName=Mickey&LastName=Mouse&action=verwerk,被隐藏div包裹的isthishidden字段会被自动排除,你需要的action隐藏域会正常保留。如果后续通过toggle把隐藏的div显示出来,对应的字段就会自动加入序列化结果。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:15:06