如何实现多步骤表单中输入项完成后激活按钮?
多步骤表单按钮按需激活实现方案
针对你的多步骤表单需求,我们可以通过监听输入变化实时校验对应步骤的必填项,以此控制按钮的启用/禁用状态,具体实现如下:
调整后的HTML结构
(修正了重复的输入框class,给按钮添加标识类并默认设置为禁用状态)
<form class="container" style="margin: 30px;"> <input type="text" class="first-name" placeholder="first name"> <input type="text" class="last-name" placeholder="last name"> <button type="button" class="next-btn" disabled>next</button> </form> <form class="container" style="margin: 30px;"> <input type="radio" id="age1" name="age" value="30"> <label for="age1">0 - 30</label><br> <input type="radio" id="age2" name="age" value="60"> <label for="age2">31 - 60</label><br> <input type="radio" id="age3" name="age" value="100"> <label for="age3">61 - 100</label><br><br> <input type="submit" class="submit-btn" value="Submit" disabled> </form>
JavaScript实现代码
// 获取所需DOM元素 const firstFormInputs = document.querySelectorAll('.container:first-of-type input'); const nextBtn = document.querySelector('.next-btn'); const ageRadios = document.querySelectorAll('input[name="age"]'); const submitBtn = document.querySelector('.submit-btn'); // 监听第一个表单的输入,控制Next按钮状态 firstFormInputs.forEach(input => { input.addEventListener('input', () => { // 检查两个输入框是否都填写了有效内容(去除首尾空格) const isFirstNameValid = document.querySelector('.first-name').value.trim() !== ''; const isLastNameValid = document.querySelector('.last-name').value.trim() !== ''; // 只有两个输入都有效时,启用Next按钮 nextBtn.disabled = !(isFirstNameValid && isLastNameValid); }); }); // 监听单选框选择变化,控制Submit按钮状态 ageRadios.forEach(radio => { radio.addEventListener('change', () => { // 检查是否有单选框被选中 const hasSelectedAge = Array.from(ageRadios).some(radio => radio.checked); // 选中后启用Submit按钮 submitBtn.disabled = !hasSelectedAge; }); });
逻辑说明
- 第一个表单(姓名步骤):监听两个输入框的
input事件,每次输入时校验两个输入框是否都有非空内容,满足条件则启用Next按钮,否则保持禁用。 - 第二个表单(年龄选择步骤):监听单选框的
change事件,只要有任意一个年龄选项被选中,就启用Submit按钮,未选中时保持禁用。
内容的提问来源于stack exchange,提问作者Frankie
相关产品推荐
相关产品推荐

