this is my first post so apologies if I get anything wrong, just let me know.
I am trying to have an external javascript file that has functions which will be able to be reused. For instance, when I have a text field and want to validate it, I want to be able to pass over three arguments (value to check, field description and min length allowed)
At the top of my HTML (above head tag) I have my script tag:
<script src="checkInputs.js"></script>
So far, I have a form. The form has these two fields (omitted some code):
<form name="join" action="createUser.php" onsubmit="return initDetails()" method="post">
<label> Choose a username: </label> <input type="text" name="username" maxlength=20><br>
<div id="uname" style="display: none; font-family:arial;color:red;font-size:12px;"></div>
The submit of the form calls the following function (I know it is calling it correctly):
function initDetails() {
alert("inside initDetails");
var unamev=document.forms["join"]["username"].value;
var pass=true;
var usernameCheck = [];
usernameCheck.push(checkTextField(unamev, 5, "username"));
alert("check variables");
alert(usernameCheck['Pass']);
alert(usernameCheck['Error']);
alert("check variables finished");
if (usernameCheck['Pass']=="True"){
alert("We pass");
document.getElementById('uname').style.display = 'none';
}
else{
alert("We fail");
pass=false;
document.getElementById('uname').style.display = 'block';
document.getElementById("uname").innerHTML = usernameCheck['Error'];
}
return pass;
}
So the above is responsible for grabbing the username, call calling checkTextField with my three values, and storing the returned items in an array. These are used to see if the test passed or failed, and populating the error message and displaying the hidden block with that error, and finally returning true or false to the submit.
So now for the external js file, I have the following:
function checkTextField(fieldInput, maxLength, fieldDescription) {
alert("Inside checkInputs.js ")
var errmsg = "";
if (fieldInput.length < maxLength ){
pass=false;
errmsg = "<li> The " + fieldDescription + " must be larger than 5 characters </li>";
if (fieldInput == null || fieldInput == ""){
pass=false;
errmsg = "<li> The " + fieldDescription + " cannot be empty </li>";
}
return {'Pass': "False", 'Error': errmsg};
}
else{
return {'Pass': "True", 'Error' : ""};
}
}
I used to have something very similar inside the HTML file that worked, but to avoid duplicated code, I wanted to have a framework of sorts to handle these. Now it could very well be that I am making a simple syntax schoolboy error, but I am trying to get up to scratch with Javascript, its not too good.
UPDATE
I have updated the code based on a number of suggestions posted here. It now calls the external file, and the following alerts:
alert(usernameCheck['Pass']);
alert(usernameCheck['Error']);
Both alerts are undefined....