Currently, I am focusing on validating user input, specifically the name to ensure it is at least 6 characters long. Although I plan to implement more validation, I am facing an issue with error display. When the JavaScript code is embedded within the HTML page, the error message is properly shown if the name is less than 6 characters.
However, when I move the JavaScript code to an external .js file, the error message does not appear as intended. Despite the code being identical, the functionality differs based on the placement of the script.
Below is the basic HTML structure for the name input section:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Registration Form</title>
<link type="text/css" rel="stylesheet" href="week12.css" />
<script type="text/javascript" src="validate.js"></script>
</head>
<body>
<div class="form">
<table>
<tr>
<td><input type="text" name="txtName" id="txtName" placeholder="Name" /></td>
<td><p class="error" id="txtNameError">Name must be at least 6 characters long.</p></td>
<!--The p class "error" is set to hidden visibility using the CSS page. If they don't meet the requirements, then "txtNameError" becomes visible.-->
</tr>
<tr>
<td><button onclick="validateForm();">Register</button></td>
</tr>
</table>
</div>
</body>
</html>
When I include the function within the HTML page itself, it successfully displays the error message. However, moving the function to validate.js results in the error message not appearing at all.
<script>
function validateForm() {
var name = document.getElementById('txtName').value;
var nameLength = name.length;
if (nameLength < 6) {
document.getElementById("txtNameError").style.visibility = "visible";
}
}
</script>
It's important to note that when the function is in an external file, the script tags are removed from the HTML page. This distinction seems to be impacting the functionality of the validation process.