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

HTML表单如何实现点击+按钮动态新增药品输入行

实现方法

你可以通过原生JS绑定按钮点击事件来动态新增输入行,具体修改如下:

  1. 首先把原有的+按钮类型从submit改为button,避免点击时触发表单提交
  2. 新增专门的容器存放药品输入行,方便后续动态追加内容
  3. 输入项的name属性改为数组格式(如medicine[]),方便后端接收多条药品数据

完整可运行代码

<html>
<body style="color:black; font-size:20px;">
<form>
    <div style="margin-bottom: 10px;">
        <label style="margin-right:95px;"> Medicine </label> 
        <label style="margin-right:135px;"> Qty. </label>
        <label> Timing-Freq-Duration </label> <br>
    </div>
    <!-- 药品输入行容器 -->
    <div id="medicineList">
        <div class="medicine-row" style="margin-bottom: 8px;">
            <input type="text" name="medicine[]" placeholder="Medicine Name">
            <input type="text" name="quantity[]">
            <input type="text" name="duration[]">
        </div>
    </div>
    <input type="button" style="margin-left:30px; margin-top: 5px;" value="+" id="addBtn">
    <input type="submit" style="margin-left:10px; margin-top: 5px;" value="提交表单">
</form>

<script>
// 绑定新增按钮点击事件
document.getElementById('addBtn').addEventListener('click', function() {
    const container = document.getElementById('medicineList');
    // 创建新的输入行
    const newRow = document.createElement('div');
    newRow.className = 'medicine-row';
    newRow.style.marginBottom = '8px';
    // 填充输入项结构,附带删除按钮
    newRow.innerHTML = `
        <input type="text" name="medicine[]" placeholder="Medicine Name">
        <input type="text" name="quantity[]">
        <input type="text" name="duration[]">
        <button type="button" style="margin-left:10px;" onclick="this.parentElement.remove()">-</button>
    `;
    container.appendChild(newRow);
})
</script>
</body>
</html>

不需要每行的删除功能的话,直接删掉代码里的button标签即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 00:39:03