纯JS实现:动态输入框全填写后激活按钮的解决方案
解决方案
核心思路是监听输入变化+批量校验所有输入框状态,以下是具体实现步骤:
1. 编写校验函数
先实现一个函数,判断所有目标输入框是否都有效填写(自动过滤纯空格的无效输入):
function checkAllInputsFilled() { // 选中所有带grade-input类的输入框 const inputs = document.querySelectorAll('.grade-input'); // 转换为数组后,用every判断每个输入框内容是否非空(trim去除首尾空格) return Array.from(inputs).every(input => input.value.trim() !== ''); }
2. 绑定输入监听事件
因为输入框是动态生成的,推荐用事件委托(监听父容器的输入事件),比给每个输入框单独绑定事件更高效:
// 找到输入框的父容器(即你创建的ul元素) const inputContainer = document.getElementById(`${CourseName}-input-ul`); // 监听容器内的所有input事件 inputContainer.addEventListener('input', () => { // 根据校验结果切换按钮禁用状态 SendAndShow.disabled = !checkAllInputsFilled(); });
如果不想用事件委托,也可以在动态创建输入框时直接绑定事件:
// 在创建text_input的代码末尾添加 text_input.addEventListener('input', () => { SendAndShow.disabled = !checkAllInputsFilled(); });
3. 完整整合后的代码
将上述逻辑整合到原有代码中,最终代码片段如下:
// 动态生成输入框的循环 (CourseObject.course_array).forEach((evaluation, value) => { const percentage_value = CourseObject.each_evaluation_value[value]; const li_inputs = document.createElement('li'); li_inputs.id = (`${evaluation}-of-${CourseName}-input-li`.replace(/°/g, "").replace(/ /g, "")).toLocaleLowerCase(); li_inputs.className = "list-group-item"; document.getElementById(`${CourseName}-input-ul`).appendChild(li_inputs); const text_input = document.createElement('input'); text_input.type = 'text'; text_input.placeholder = `Nota de ${evaluation} (${percentage_value}%)`; text_input.id = (`${evaluation}-of-${CourseName}-input-text`.replace(/°/g, "").replace(/ /g, "")).toLocaleLowerCase(); text_input.className = 'form-control grade-input'; li_inputs.appendChild(text_input); // 直接用变量插入,避免重复通过id查找元素 // 可选:单个输入框绑定事件(不用事件委托时启用) // text_input.addEventListener('input', () => { // SendAndShow.disabled = !checkAllInputsFilled(); // }); }); // 创建按钮 const SendAndShow = document.createElement('button'); SendAndShow.textContent = 'Calcular'; SendAndShow.id = 'send-and-show-button'; SendAndShow.disabled = true; SendAndShow.className = 'btn btn-dark'; document.getElementById('second-column').appendChild(SendAndShow); // 校验函数 function checkAllInputsFilled() { const inputs = document.querySelectorAll('.grade-input'); return Array.from(inputs).every(input => input.value.trim() !== ''); } // 事件委托方案(推荐) const inputContainer = document.getElementById(`${CourseName}-input-ul`); inputContainer.addEventListener('input', () => { SendAndShow.disabled = !checkAllInputsFilled(); }); // 按钮点击事件 document.getElementById('send-and-show-button').onclick = function() { // 你的业务逻辑代码 };
关键注意点
- 使用
trim()是为了避免用户仅输入空格就被判定为已填写的情况 - 事件委托更适合动态生成的元素,无需在创建每个元素时重复绑定事件,性能更优
querySelectorAll返回的是NodeList,需要通过Array.from()转换为数组后才能使用every方法
内容的提问来源于stack exchange,提问作者Luis Felipe Rodriguez
相关产品推荐
相关产品推荐

