JS 修改表单name下标的问题

本文介绍了一种使用jQuery实现的动态添加和删除表单项的方法,适用于需要收集多个相同类型输入项的场景,如批量录入数据。通过点击按钮,可以在页面上动态生成包含标题和用户名输入框的列表项,并提供了删除已生成项的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 <ul id="listUl"></ul>
  <button id="add">添加</button>
  <script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
 var index=0;
 $("#add").click(function(){
   var html='';
    html+='<li class="ItemUl">';
    html+='<input type="text" data-value="title" name="user['+index+'].title" lay-verify="title" autocomplete="off" placeholder="请输入标题" class="layui-input">';
    html+='<input type="text" data-value="username" name="user['+index+'].username" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">';
    html+='<button onclick="del(this)">删除</button>';
    html+='</li>'; 
   $("#listUl").append(html);
   index ++;
 })

 //删除
function del(that){
    $(that).parent().remove();
 	var items=$(".ItemUl")
 	index=items.length;
    items.each(function (i) {
   	   var inputs =$(this).find("input");
   	   inputs.each(function () {
             var inp = $(this).data("value");
             $(this).attr("name", "user[" + i + "]." + inp);
        });
    })
 }
</script>

  

转载于:https://www.cnblogs.com/lemonmoney/p/9717482.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值