微风拂过
带来远处花香与青草的气息

创建有效的多步骤表单以获得更好的用户体验

众所周知,表单很难定制和设计样式——在某种程度上,我们已经开始看到更灵活控制的新想法。但我们不常讨论的是如何设计超越验证的好形式体验。这就是在本文中讨论的内容,特别关注如何创建包含各节之间导航的多步骤表单。

对于多步骤表单,计划包括跨步骤逻辑地组织问题,对相似的问题进行分组,并尽量减少步骤的数量和每个步骤所需的信息量。任何能让每一步都有重点且易于管理的东西,都应该是你的目标。

在本教程中,我们将为工作申请创建一个多步骤表单。以下是我们在每个步骤中将要求申请人提供的详细信息:

  • 个人信息
    收集申请人的姓名、电子邮件和电话号码。
  • 工作经验
    收集申请人最近的公司、职位和工作年限。
  • 技能与资历
    申请人列出他们的技能并选择他们的最高学位。
  • 审核与提交
    这一步不会收集任何信息。相反,它为申请人提供了一个机会,可以在提交表单之前返回并查看在表单的前面步骤中输入的信息。

你可以把这些问题想象成一种了解某人的数字化方式。你不可能在第一次见到某人时不先问他们的名字就询问他们的工作经历。

根据上面的步骤,这就是我们的HTML正文和表单应该是什么样子的。首先,主元素form

<form id="jobApplicationForm">
  <!-- Step 1: Personal Information -->
  <!-- Step 2: Work Experience -->
  <!-- Step 3: Skills & Qualifications -->
  <!-- Step 4: Review & Submit -->
</form>

Step 1

第一步是填写个人信息,如申请人的姓名、电子邮件地址、电话号码;

<form id="jobApplicationForm">
  <!-- Step 1: Personal Information -->
  <fieldset class="step" id="step-1">
    <legend id="step1Label">Step 1: Personal Information</legend>
    <label for="name">Full Name</label>
    <input type="text" id="name" name="name" required />
    <label for="email">Email Address</label>
    <input type="email" id="email" name="email" required />
    <label for="phone">Phone Number</label>
    <input type="tel" id="phone" name="phone" required />
  </fieldset>
  <!-- Step 2: Work Experience -->
  <!-- Step 3: Skills & Qualifications -->
  <!-- Step 4: Review & Submit -->
</form>

Step 2

一旦申请人完成第一步,我们将引导他们进入第二步,重点了解其工作经历,以便收集诸如其最近就职的公司、职位以及工作年限等信息。我们将添加一个新的<fieldset>并输入这些内容:

<form id="jobApplicationForm">
  <!-- Step 1: Personal Information -->

  <!-- Step 2: Work Experience -->
  <fieldset class="step" id="step-2" hidden>
    <legend id="step2Label">Step 2: Work Experience</legend>
    <label for="company">Most Recent Company</label>
    <input type="text" id="company" name="company" required />
    <label for="jobTitle">Job Title</label>
    <input type="text" id="jobTitle" name="jobTitle" required />
    <label for="yearsExperience">Years of Experience</label>
    <input
      type="number"
      id="yearsExperience"
      name="yearsExperience"
      min="0"
      required
    />
  </fieldset>

  <!-- Step 3: Skills & Qualifications -->
  <!-- Step 4: Review & Submit -->
</form>

Step 3

第三步是求职者列出他们所申请工作的技能和资格:

<form id="jobApplicationForm">
  <!-- Step 1: Personal Information -->
  <!-- Step 2: Work Experience -->

  <!-- Step 3: Skills & Qualifications -->
  <fieldset class="step" id="step-3" hidden>
    <legend id="step3Label">Step 3: Skills & Qualifications</legend>
    <label for="skills">Skill(s)</label>
    <textarea id="skills" name="skills" rows="4" required></textarea>
    <label for="highestDegree">Degree Obtained (Highest)</label>
    <select id="highestDegree" name="highestDegree" required>
      <option value="">Select Degree</option>
      <option value="highschool">High School Diploma</option>
      <option value="bachelor">Bachelor's Degree</option>
      <option value="master">Master's Degree</option>
      <option value="phd">Ph.D.</option>
    </select>
  </fieldset>
  <!-- Step 4: Review & Submit -->
  <fieldset class="step" id="step-4" hidden>
    <legend id="step4Label">Step 4: Review & Submit</legend>
    <p>Review your information before submitting the application.</p>
    <button type="submit">Submit Application</button>
  </fieldset>
</form>

最后,我们将允许申请人在提交之前查看他们的信息:

<form id="jobApplicationForm">
  <!-- Step 1: Personal Information -->
  <!-- Step 2: Work Experience -->
  <!-- Step 3: Skills & Qualifications -->

  <!-- Step 4: Review & Submit -->
  <fieldset class="step" id="step-4" hidden>
    <legend id="step4Label">Step 4: Review & Submit</legend>
    <p>Review your information before submitting the application.</p>
    <button type="submit">Submit Application</button>
  </fieldset>
</form>

注意:我们已经为每个 fieldset 元素添加了 hidden 属性,但第一个元素除外。这样可以确保用户只看到第一步。一旦他们完成了第一步,他们可以通过单击导航按钮在第二步中继续填写他们的工作经验。稍后我们将添加此按钮。 添加样式#

为了保持重点,我们不打算在本教程中强调样式。为了保持简单,我们将利用simple .css样式框架使表单在本教程的其余部分保持良好的形状。

如果你在跟随,我们可以包括Simple的样式在文档 head :

<link rel="stylesheet" href="https://cdn.simplecss.org/simple.min.css" />

然后从那里,继续创建一个 style.css 文件,我折叠了以下样式。

<details>
  <summary>View CSS</summary>
  body {
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  main {
    padding: 0 30px;
  }
  h1 {
    font-size: 1.8rem;
    text-align: center;
  }
  .stepper {
    display: flex;
    justify-content: flex-end;
    padding-right: 10px;
  }
  form {
    box-shadow: 0px 0px 6px 2px rgba(0, 0, 0, 0.2);
    padding: 12px;
  }
  input,
  textarea,
  select {
    outline: none;
  }
  input:valid,
  textarea:valid,
  select:valid,
  input:focus:valid,
  textarea:focus:valid,
  select:focus:valid {
    border-color: green;
  }
  input:focus:invalid,
  textarea:focus:invalid,
  select:focus:invalid {
    border: 1px solid red;
  }
</details>

表单导航和验证

验证多步骤表单的用户体验的一个简单方法是,等到用户到达表单的最后一步,才让他们知道他们在此过程中犯了什么错误。在进入下一步之前,应该验证表单的每个步骤是否存在错误,并且应该显示描述性错误消息,以便用户了解错误所在以及如何修复它。

现在,表单中唯一可见的部分是第一步。要完成表单,用户需要能够导航到其他步骤。我们要用几个按钮把它拉下来。第一步将有一个Next按钮。第二步和第三步都将有一个Previous和一个Next按钮,第四步将有一个Previous和一个Submit按钮。

<form id="jobApplicationForm">
  <!-- Step 1: Personal Information -->
  <fieldset>
    <!-- ... -->
    <button type="button" class="next" onclick="nextStep()">Next</button>
  </fieldset>

  <!-- Step 2: Work Experience -->
  <fieldset>
    <!-- ... -->
    <button type="button" class="previous" onclick="previousStep()">Previous</button>
    <button type="button" class="next" onclick="nextStep()">Next</button>
  </fieldset>

  <!-- Step 3: Skills & Qualifications -->
  <fieldset>
    <!-- ... -->
    <button type="button" class="previous" onclick="previousStep()">Previous</button>
    <button type="button" class="next" onclick="nextStep()">Next</button>
  </fieldset>

  <!-- Step 4: Review & Submit -->
  <fieldset>
    <!-- ... -->
    <button type="button" class="previous" onclick="previousStep()">Previous</button>
    <button type="submit">Submit Application</button>
  </fieldset>
</form>

注意:我们已经为Previous和Next按钮添加了 onclick 属性,以将它们链接到各自的JavaScript函数: previousStep() 和 nextStep() 。

“下一步”按钮

 nextStep() 函数链接到Next按钮。每当用户单击Next按钮时, nextStep() 函数将首先检查以确保用户所处的任何步骤的所有字段都已正确填写,然后再转到下一步。如果字段没有被正确填充,它会显示一些错误消息,让用户知道他们做错了什么,并通知他们做什么来消除错误。

在我们进入 nextStep 函数的实现之前,我们需要定义一些变量,因为它们将在函数中使用。首先,我们需要DOM中的输入字段,这样我们就可以对它们进行检查,以确保它们是有效的。

// Step 1 fields
const name = document.getElementById("name");
const email = document.getElementById("email");
const phone = document.getElementById("phone");

// Step 2 fields
const company = document.getElementById("company");
const jobTitle = document.getElementById("jobTitle");
const yearsExperience = document.getElementById("yearsExperience");

// Step 3 fields
const skills = document.getElementById("skills");
const highestDegree = document.getElementById("highestDegree");

然后,我们需要一个数组来存储错误消息。

let errorMsgs = [];

此外,我们还需要在DOM中添加一个元素,以便在生成错误消息后插入这些消息。这个元素应该放在HTML中最后一个 fieldset 结束标签的下面:

<div id="errorMessages" style="color: rgb(253, 67, 67)"></div>

将上面的 div 添加到JavaScript代码中,使用以下行:

const errorMessagesDiv = document.getElementById("errorMessages");

最后,我们需要一个变量来记录当前的步长。

let currentStep = 1;

现在我们已经把所有的变量都准备好了,下面是 nextstep() 函数的实现:

function nextStep() {
  errorMsgs = [];
  errorMessagesDiv.innerText = "";

  switch (currentStep) {
    case 1:
      addValidationErrors(name, email, phone);
      validateStep(errorMsgs);
      break;

    case 2:
      addValidationErrors(company, jobTitle, yearsExperience);
      validateStep(errorMsgs);
      break;

    case 3:
      addValidationErrors(skills, highestDegree);
      validateStep(errorMsgs);
      break;
  }
}

在按下Next按钮的那一刻,我们的代码首先检查用户当前所处的步骤,并根据这些信息,通过调用 addValidationErrors() 函数来验证该特定步骤的数据。如果有错误,我们显示它们。然后,表单调用 validateStep() 函数来验证在进入下一步之前没有错误。如果有错误,它将阻止用户继续进行下一步。

每当 nextStep() 函数运行时,错误消息首先被清除,以避免在 addValidationErrors 函数运行时将来自不同步骤的错误追加到现有错误或重新添加现有错误消息。 addValidationErrors 函数使用该步骤的字段作为参数对每个步骤调用。

下面是 addValidationErrors 函数的实现:

function addValidationErrors(fieldOne, fieldTwo, fieldThree = undefined) {
  if (!fieldOne.checkValidity()) {
    const label = document.querySelector(`label[for="${fieldOne.id}"]`);
    errorMsgs.push(`Please Enter A Valid ${label.textContent}`);
  }

  if (!fieldTwo.checkValidity()) {
    const label = document.querySelector(`label[for="${fieldTwo.id}"]`);
    errorMsgs.push(`Please Enter A Valid ${label.textContent}`);
  }

  if (fieldThree && !fieldThree.checkValidity()) {
    const label = document.querySelector(`label[for="${fieldThree.id}"]`);
    errorMsgs.push(`Please Enter A Valid ${label.textContent}`);
  }

  if (errorMsgs.length > 0) {
    errorMessagesDiv.innerText = errorMsgs.join("\n");
  }
}

下面是 validateStep() 函数的定义:

function validateStep(errorMsgs) {
  if (errorMsgs.length === 0) {
    showStep(currentStep + 1);
  }
}

 validateStep() 函数检查错误。如果没有,则在 showStep() 函数的帮助下进行下一步。

function showStep(step) {
  steps.forEach((el, index) => {
    el.hidden = index + 1 !== step;
  });
  currentStep = step;
}

 showStep() 函数需要DOM中的四个字段集。将以下行添加到JavaScript代码的顶部以使字段集可用:

const steps = document.querySelectorAll(".step");

 showStep() 函数的作用是遍历表单中的所有 fieldsets 并隐藏任何 fieldset 不等于我们要导航到的那个。然后,它更新 currentStep 变量,使其等于我们要导航到的步骤。

“上一页”按钮

 previousStep() 函数链接到上一页按钮。每当单击上一个按钮时,与 nextStep 函数类似,错误消息也从页面中清除,并且导航也由 showStep 函数处理。

function previousStep() {
  errorMessagesDiv.innerText = "";
  showStep(currentStep - 1);
}

每当 showStep() 函数被调用时,以“ currentStep - 1 ”作为参数(就像在这个例子中一样),我们回到上一步,而通过调用 showStep() 函数,以“ currentStep + 1 ”作为参数(就像在 validateStep() 函数的情况下)来移动到下一步。

利用视觉提示改善用户体验

另一种改善多步骤表单用户体验的方法是整合视觉线索,这些线索会给用户提供他们所处过程的反馈。这些东西可以包括进度指示器或步进器,以帮助用户知道他们所处的确切步骤。

对A步进#积分

要将步进器集成到表单中(类似于Material Design中的步进器),我们需要做的第一件事是将它添加到HTML中,就在 <form> 标签下方。

<form id="jobApplicationForm">
  <div class="stepper">
    <span><span class="currentStep">1</span>/4</span>
  </div>
  <!-- ... -->
</form>

接下来,我们需要查询表示当前步骤的步进部分。这是类名为 currentStep 的span标签。

const currentStepDiv = document.querySelector(".currentStep");

现在,我们需要在单击previous或next按钮时更新步进值。为此,我们需要更新 showStep() 函数,向其添加以下行:

currentStepDiv.innerText = currentStep;

这一行被添加到 showStep() 函数中,因为 showStep() 函数负责在步骤之间导航并更新 currentStep 变量。因此,每当 currentStep 变量更新时,currentStepDiv也应该更新以反映该更改。

存储和检索用户数据#

改善表单用户体验的一个主要方法是将用户数据存储在浏览器中。多步骤表单通常很长,需要用户输入大量关于自己的信息。想象一下,用户填写了95%的表单,然后不小心按下了键盘上的F5按钮,失去了所有的进度。这对用户来说将是一个非常糟糕的体验。

使用 localStorage ,我们可以在输入用户信息后立即存储用户信息,并在加载DOM内容后立即检索用户信息,这样用户就可以从他们离开的任何地方继续填写表单。要将这个特性添加到表单中,我们可以在输入用户信息后立即保存它。这可以使用 input 事件来实现。

在添加 input 事件监听器之前,先从DOM中获取form元素:

const form = document.getElementById("jobApplicationForm");

Now we can add the input event listener:现在我们可以添加 input 事件监听器:

// Save data on each input event
form.addEventListener("input", () => {
  const formData = {
    name: document.getElementById("name").value,
    email: document.getElementById("email").value,
    phone: document.getElementById("phone").value,
    company: document.getElementById("company").value,
    jobTitle: document.getElementById("jobTitle").value,
    yearsExperience: document.getElementById("yearsExperience").value,
    skills: document.getElementById("skills").value,
    highestDegree: document.getElementById("highestDegree").value,
  };
  localStorage.setItem("formData", JSON.stringify(formData));
});

接下来,我们需要添加一些代码来帮助我们在加载DOM内容后检索用户数据。

window.addEventListener("DOMContentLoaded", () => {
  const savedData = JSON.parse(localStorage.getItem("formData"));
  if (savedData) {
    document.getElementById("name").value = savedData.name || "";
    document.getElementById("email").value = savedData.email || "";
    document.getElementById("phone").value = savedData.phone || "";
    document.getElementById("company").value = savedData.company || "";
    document.getElementById("jobTitle").value = savedData.jobTitle || "";
    document.getElementById("yearsExperience").value = savedData.yearsExperience || "";
    document.getElementById("skills").value = savedData.skills || "";
    document.getElementById("highestDegree").value = savedData.highestDegree || "";
  }
});

最后,最好在不再需要的时候从 localStorage 中删除数据:

// Clear data on form submit
form.addEventListener('submit', () => {
  // Clear localStorage once the form is submitted
  localStorage.removeItem('formData');
}); 

将当前步长值添加到 localStorage  #

如果用户不小心关闭了浏览器,他们应该能够回到他们离开的地方。这意味着当前步长值也必须保存在 localStorage 中。

为了保存该值,将以下行添加到 showStep() 函数中:

localStorage.setItem("storedStep", currentStep);

现在我们可以检索当前步长值,并在加载DOM内容时将用户返回到他们离开的位置。在 DOMContentLoaded 处理程序中添加以下代码:

const storedStep = localStorage.getItem("storedStep");

if (storedStep) {
    const storedStepInt = parseInt(storedStep);
    steps.forEach((el, index) => {
      el.hidden = index + 1 !== storedStepInt;
    });
    currentStep = storedStepInt;
    currentStepDiv.innerText = currentStep;
  }

此外,不要忘记在提交表单时清除 localStorage 中的当前步长值。

localStorage.removeItem("storedStep");

上面这行应该添加到提交处理程序中。

总结#

创建多步骤表单有助于改善复杂数据输入的用户体验。通过仔细规划步骤,在每个步骤中实现表单验证,并将用户数据临时存储在浏览器中,可以使用户更容易完成长表单。

赞(0) 打赏
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:创建有效的多步骤表单以获得更好的用户体验
文章链接:https://www.fec.xyz/course/2025-230.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。

评论 抢沙发

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

微信扫一扫

登录

找回密码

注册