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

如何用JS将多步骤表单的输入值传递至下一步?

实现多步骤表单中输入值跨步骤传递

直接修改你的nextSection函数,在切换到第二步时同步输入值即可,另外你的Step2标签id写错了(原代码是step,修正为step2避免选择器问题),以下是完整解决方案:

修改后的JavaScript代码

const prevBtn = document.querySelectorAll(".prev-btn");
const nextBtn = document.querySelectorAll(".next-btn");
let currentSection = 0;

function showSection(sectionIndex) {
  const sections = document.querySelectorAll(".steps");
  sections[currentSection].classList.remove("active-step");
  sections[sectionIndex].classList.add("active-step");
  currentSection = sectionIndex;
}

function nextSection() {
  if (currentSection < 2) {
    // 从Step1切换到Step2时,同步输入的名字
    if (currentSection === 0) {
      const firstNameInput = document.getElementById('firstname-input');
      const firstNameDisplay = document.getElementById('firstname');
      // 为空时显示默认值Guest,也可以留空
      firstNameDisplay.textContent = firstNameInput.value.trim() || 'Guest';
    }
    showSection(currentSection + 1);
  }
}

function prevSection() {
  if (currentSection > 0) {
    showSection(currentSection - 1);
  }
}

修正后的HTML(核心是Step2的id)

<form action="">
    <!-- Step1 -->
    <div class="steps active-step" id="step1">
        <div class="step-title">What's your first name?</div>
        <div class="step-content">
            <div class="input-area">
                <input type="text" class="text-input" placeholder="First Name" id="firstname-input">
            </div>
        </div>
        <div class="btn-next-box">
            <button onclick="nextSection()" class="next-btn" id="step1-next">Next</button>
        </div>
    </div>


    <!-- Step2 -->
    <div class="steps" id="step2">
        <button onclick="prevSection()" class="prev-btn">Prev</button>
        <div class="step-title"><span id="firstname"></span>, which club you're in?</div>
        <div class="step-content">
            <div class="input-area">
                <input type="text" class="text-input" placeholder="your club name" id="club-input">
            </div>
        </div>
        <div class="btn-next-box">
            <button onclick="nextSection()" class="next-btn" id="step2-next">Next</button>
        </div>
    </div>
</form>

可选优化:实时同步输入值

如果想让用户输入名字时,Step2的标签实时更新(无需等待点击Next),可以在JS开头添加这段监听代码:

document.getElementById('firstname-input').addEventListener('input', function(e) {
  const firstNameDisplay = document.getElementById('firstname');
  firstNameDisplay.textContent = e.target.value.trim() || 'Guest';
});

这样用户输入过程中,返回Step2也能看到最新的名字,体验更流畅。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 14:52:40