登录表单JavaScript校验报错:Uncaught TypeError: Cannot read properties of undefined (reading 'uname') 求助排查
Hey there! Let's break down why you're hitting that error and get your validation working as expected.
Root Cause of the Error
The Uncaught TypeError happens because your JavaScript is trying to access document.forms["myform"], but your HTML form only has class="myform"—document.forms uses the form's name attribute to find elements, not the class attribute. This means document.forms["myform"] returns undefined, and trying to read .uname from an undefined value throws the error you're seeing.
Quick Fixes to Get Your Validation Working
Fix 1: Add a name Attribute to Your Form
The simplest fix is to add a name attribute matching what your JS expects to the form tag. Update your HTML form like this:
<form name="myform" class="myform" onsubmit="return vfun()">
Now document.forms["myform"] will correctly locate your form, and the rest of your validation logic will run as intended.
Fix 2: Use getElementById for More Robust Form Selection
If you prefer not to rely on the name attribute, you can use an id instead. Here's how:
- Update your HTML form to include an
id:
<form id="myform" class="myform" onsubmit="return vfun()">
- Modify your JavaScript function to fetch the form by its
id:
function vfun(){ const form = document.getElementById("myform"); const uname = form["uname"].value; const pword = form["pword"].value; if (!uname) { document.getElementById("errorBox").textContent = "enter the user name"; return false; } if (!pword) { document.getElementById("errorBox").textContent = "enter the password"; return false; } alert("Login successfully"); return true; }
(Note: I swapped innerHTML for textContent here—it's safer for plain text content like error messages.)
Bonus: Improve Error Message Experience
Right now, if both fields are empty, only the username error shows up. You could adjust the logic to show both errors if needed:
function vfun(){ const form = document.getElementById("myform"); const uname = form["uname"].value; const pword = form["pword"].value; const errorBox = document.getElementById("errorBox"); let errors = []; if (!uname) errors.push("enter the user name"); if (!pword) errors.push("enter the password"); if (errors.length > 0) { errorBox.textContent = errors.join(", "); return false; } alert("Login successfully"); return true; }
内容的提问来源于stack exchange,提问作者Harish R

