Today I am going to show you how to write a simple JavaScript function. The scenario is, by the time I click my submit button if there are empty text fields in the form, an alert message will display with the help of JavaScript.
Fist I will show my form interface.
I am going to write the JavaScript for the onclick function of the Submit button. If the Username text box is empty, then it will display an alert message like below.
You have to include following code with in these tags;
<script type=”text/javascript”> … </script>
... function loginvalidation(){ if(document.login.textfieldUsername.value == ""){ alert("Username cannot be empty"); return (false); }else if(document.login.textfieldPassword.value == ""){ alert("Password cannot be empty"); return(false); } } ...
login is my form id, textfiledUsername is the id relevant to Username field and textfieldPassword is the other id. The most important thing is, you have to add the above written JavaScript in to the onclick function of the Submit button as follow.
... input type="submit" name="buttonSubmit" id="buttonSubmit" value="Submit" onclick="javascript: return loginvalidation()" ...
That’s all about today’s post. Thank you 🙂