JavaScript表单输入非空校验报错:Uncaught TypeError问题求助
问题分析与解决方案
原代码错误点
document.querySelectorAll(".formInputOne").value:querySelectorAll返回的是NodeList集合,没有.value属性,直接取值会得到undefined,这就是报错Cannot read properties of undefined reading 'forEach'的核心原因。if (formInputOne.forEach == ""):逻辑完全错误,forEach是集合的遍历方法,不能和空字符串做比较,也无法通过这种方式判断输入框是否为空。
原生JavaScript解决方案
先获取所有目标输入框,遍历检查每个输入框的value(去除首尾空格,避免用户输入无效空格),只要有一个为空,就判定为未填完。
基础实现代码
<form> <input class="formInputOne" /> <input class="formInputOne" /> <input class="formInputOne" /> <input class="button" type="submit" /> </form> <script> const button = document.querySelector('.button'); button.addEventListener("click", function (e) { // 阻止表单默认提交行为,避免页面刷新 e.preventDefault(); const inputs = document.querySelectorAll(".formInputOne"); let allFilled = true; inputs.forEach(input => { if (input.value.trim() === "") { allFilled = false; } }); if (!allFilled) { console.log("All fields are required!"); } else { console.log("Yay! All fields got values"); // 如需提交表单,可在此添加 form.submit() } }); </script>
简洁优化写法(使用every方法)
button.addEventListener("click", function (e) { e.preventDefault(); const inputs = document.querySelectorAll(".formInputOne"); // every方法检查所有元素是否满足条件,只要有一个不满足就返回false const allFilled = Array.from(inputs).every(input => input.value.trim() !== ""); if (!allFilled) { console.log("All fields are required!"); } else { console.log("Yay! All fields got values"); } });
注:现代浏览器中
NodeList已支持every方法,旧浏览器可通过Array.from()转成数组兼容。
jQuery解决方案
使用jQuery代码会更简洁:
基础实现代码
<form> <input class="formInputOne" /> <input class="formInputOne" /> <input class="formInputOne" /> <input class="button" type="submit" /> </form> <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script> <script> $('.button').on('click', function(e) { e.preventDefault(); let allFilled = true; $('.formInputOne').each(function() { if ($(this).val().trim() === "") { allFilled = false; return false; // 提前终止遍历 } }); if (!allFilled) { console.log("All fields are required!"); } else { console.log("Yay! All fields got values"); } }); </script>
简洁写法
$('.button').on('click', function(e) { e.preventDefault(); const allFilled = $('.formInputOne').filter(function() { return $(this).val().trim() === ""; }).length === 0; allFilled ? console.log("Yay! All fields got values") : console.log("All fields are required!"); });
内容的提问来源于stack exchange,提问作者youngP
相关产品推荐
相关产品推荐

