Reputation: 83
I have created a form and I want my JavaScript to validate my form by checking whether the length of the persons name is > 20
. If it is I am trying to make a popup alert appear but it is not working. It does nothing.
This is my HTML:
<form name = "enrol" onsubmit="validate()">
<h3>Please complete the form below. Mandatory fields marked with *</h3>
<fieldset>
<h4>Personal Details</h4>
<p>
<label for="fname">*First Name</label> <input type="text" name="fname" id="fname" placeholder="First Name" />
</p>
<p>
<label for="lname">*Last Name</label> <input type="text" name="lname" id="lname" placeholder="Last Name" />
</p>
</fieldset>
</form>
This is my JavaScript they are connected through referencing. All other scripts work except function validate ()
window.onload = function() {
console.log("The window has finished loading");
var SubmitButton = document.getElementById("SubmitButton");
SubmitButton.addEventListener('click', function() {
document.getElementById("SubmitButton").click();
}, false);
console.log("The submit button has been clicked");
var fname = document.getElementById("fname");
fname.addEventListener('keyup', function() {
console.log((fname).value);
}, false);
var lname = document.getElementById("lname");
lname.addEventListener('keyup', function() {
console.log((lname).value);
}, false);
function validate(){
var fname = document.enrol.fname.value;
var lname=document.enrol.lname.value;
if(fname.length>20){
alert("Value can't exceed 20");
}
if(lname.length>20){
alert("Value can't exceed 20");
}
}
Upvotes: 1
Views: 189
Reputation: 38103
This is because the validate()
function is not accessible in the global scope. The reason for this is because it is inside the anonymous function being assigned to window.onload
, and thus is only valid to be called inside that function.
To fix it, just move it after the closing }
for the window.onload
function.
Upvotes: 0
Reputation: 5222
Put that validate
function outside of window.onload
event handler.
window.onload = function() {
console.log("The window has finished loading");
var SubmitButton = document.getElementById("SubmitButton");
SubmitButton.addEventListener('click', function() {
document.getElementById("SubmitButton").click();}, false);
console.log("The submit button has been clicked");
var fname = document.getElementById("fname");
fname.addEventListener('keyup', function() {
console.log((fname).value);}, false);
var lname = document.getElementById("lname");
lname.addEventListener('keyup', function() {
console.log((lname).value);}, false);
}
function validate()
{
var fname = document.enrol.fname.value;
var lname=document.enrol.lname.value;
if(fname.length>20)
{
alert("Value can't exceed 20");
}
if(lname.length>20)
{
alert("Value can't exceed 20");
}
}
Upvotes: 1