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

如何在Streamlit中实现点击按钮逐行新增文本输入框

点击按钮逐行新增文本输入框实现方案

核心实现逻辑

  • 页面预置触发按钮和用于承载动态输入框的容器
  • 给按钮绑定点击事件,每次触发时创建新的文本输入框元素,追加到容器底部
  • 可通过计数器给输入框添加唯一标识,方便后续表单提交时取值

完整可运行代码示例

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>动态新增输入框</title>
    <style>
        /* 控制输入框排版样式,可按需调整 */
        .input-row {
            margin: 12px 0;
        }
        .input-row input {
            padding: 6px 12px;
            width: 320px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        #addInputBtn {
            padding: 6px 16px;
            cursor: pointer;
            border: 1px solid #1677ff;
            background: #1677ff;
            color: #fff;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <button id="addInputBtn">添加输入框</button>
    <div id="inputBoxContainer"></div>

    <script>
        const addBtn = document.getElementById('addInputBtn');
        const container = document.getElementById('inputBoxContainer');
        // 输入框计数器,用于生成唯一name/ID
        let inputIndex = 0;

        addBtn.addEventListener('click', function() {
            inputIndex++;
            // 创建输入框行容器
            const row = document.createElement('div');
            row.className = 'input-row';
            // 创建文本输入框
            const input = document.createElement('input');
            input.type = 'text';
            input.name = `dynamic_input_${inputIndex}`;
            input.placeholder = `请输入第${inputIndex}项内容`;
            // 组装元素插入页面
            row.appendChild(input);
            container.appendChild(row);
            // 可选:新增后自动聚焦到当前输入框
            input.focus();
        })
    </script>
</body>
</html>

扩展说明

如果需要支持删除单个输入框,只需要在创建input-row时同时新增删除按钮,给删除按钮绑定点击事件,移除当前input-row元素即可。

内容的提问来源于stack exchange,提问作者Pratyush Priyam Kuanr

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 15:06:07