Disable Button for form - javascript

I have a simple form. Ive tried to disable the the submit button until fields have been filled out, however it seems to not be working. can anyone point me in the right direction to what I'm doing wrong.
<form id="casmansForm">
Name: <input type="name" id="userName" class="inputs"><br>
Email: <input type="name" id="userName" class="inputs"><br>
Text: <input type="name" id="userName" class="inputs"><br>
<input type="submit" id="userSubmit" disabled><br>
</form>
<div id='alertMessage'></div>
var userName = document.getElementById('userName');
var userEmail = document.getElementById('userEmail');
var userText = document.getElementById('userText');
var userSubmit = document.getElementById('userSubmit');
var alertMessage = document.getElementById('alertMessage');
function checkForm(){
if(userName.value == "" || userEmail.value == "" || userText.value == "")
{
alertMessage.innerHTML = 'Please fill in form correctly';
userSubmit.disabled = true;
return false;
} else {
alertMessage.innerHTML = 'Thank you for filling in form';
userSubmit.disabled = false;
return true;
}
}
userName.addEventListener("blur",checkForm,false);
userEmail.addEventListener("blur",checkForm,false);
userText.addEventListener("blur",checkForm,false);

Your main issue is that you have used the same id on more than one element. ids must be unique within a document.
Also, return false is not doing anything for you in this context.
Lastly, don't use .innerHTML when you aren't supplying any HTML, use textContent for that instead.
var userName = document.getElementById('userName');
var userEmail = document.getElementById('userEmail');
var userText = document.getElementById('userText');
var userSubmit = document.getElementById('userSubmit');
var alertMessage = document.getElementById('alertMessage');
function checkForm(){
if(userName.value == "" || userEmail.value == "" || userText.value == "") {
alertMessage.textContent = 'Please fill in form correctly';
userSubmit.disabled = true;
} else {
alertMessage.textContent = 'Thank you for filling in form';
userSubmit.disabled = false;
}
}
userName.addEventListener("blur",checkForm,false);
userEmail.addEventListener("blur",checkForm,false);
userText.addEventListener("blur",checkForm,false);
<form id="casmansForm">
Name: <input type="name" id="userName" class="inputs"><br>
Email: <input type="name" id="userEmail" class="inputs"><br>
Text: <input type="name" id="userText" class="inputs"><br>
<input type="submit" id="userSubmit" disabled>
</form>
<div id='alertMessage'></div>

Related

Why the paragraphs arent showing up when inputs are empty

im pretty new to coding and i wanted to try to make a register form and use javascript to check if any of the forms are empty. I tried to make it using DOM but it seems that its not working. If anyone can help me i will be really thankful.
js code:
let btnCheck = document.querySelector('#claim');
let input = document.querySelectorAll('input');
let fname = document.querySelector('#fname');
let lname = document.querySelector('#lname');
let email = document.querySelector('#email');
let password = document.querySelector('#password');
function checkForBlank(){
if (document.querySelector('#fname').value == ""){
fname.innerHTML = 'First Name cannot be empty'
}
if (document.querySelector('#lname').value == ""){
lname.innerHTML = 'Last Name cannot be empty'
}
if (document.querySelector('#email').value == ""){
email.innerHTML = "Looks like this is not an email"
}
if (document.querySelector('#password').value ==""){
password.innerHTML = 'Password cannot be empty'
}
}
btnCheck.addEventListener('click', checkForBlank());
html code:
<form>
<input type='text' placeholder="First Name">
<p id='fname'></p>
<input type='text' placeholder="Last Name">
<p id='lname'></p>
<input type='text' placeholder="Email Address">
<p id='email'></p>
<input type='password' placeholder="Password">
<p id='password'></p>
</form>
Your code does not check to see if the form input field is empty currently. You would want to get reference to the input and check to see if that is empty.
<form>
<input id="fname-input" type="text" placeholder="First Name" />
<p id="fname"></p>
<input id="lname-input" type="text" placeholder="Last Name" />
<p id="lname"></p>
<input id="email-input" type="text" placeholder="Email Address" />
<p id="email"></p>
<input id="password-input" type="password" placeholder="Password" />
<p id="password"></p>
</form>
const btnCheck = document.querySelector('#claim');
const fname = document.querySelector('#fname');
const fnameInput = document.querySelector('#fname-input');
const lname = document.querySelector('#lname');
const lnameInput = document.querySelector('#lname-input');
const email = document.querySelector('#email');
const emailInput = document.querySelector('#email-input');
const password = document.querySelector('#password');
const passwordInput = document.querySelector('#password-input');
function checkForBlank() {
if (fnameInput.value == "") {
fname.innerHTML = "First Name cannot be empty";
}
if (lnameInput.value == "") {
lname.innerHTML = "Last Name cannot be empty";
}
if (emailInput.value == "") {
email.innerHTML = "Looks like this is not an email";
}
if (passwordInput.value == "") {
password.innerHTML = "Password cannot be empty";
}
}
btnCheck.addEventListener('click', checkForBlank);
Additionally, you need to pass a function reference to addEventListener instead of invoking the function.
btnCheck.addEventListener('click', checkForBlank()); // WRONG
btnCheck.addEventListener('click', checkForBlank); //RIGHT
Note: I would recommend to rather (or additionally) use the required property of html elements https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/required
There are multiple things that you need to refactor
It would be better to create a new HTML element for errors with different classes.
As you are wrapping the inputs in the form element, So you need to preventDefault.
For clickListener you need to pass the function reference only, no need to execute the function
// INPUTS
let btnCheck = document.querySelector('#claim');
let fname = document.querySelector('#fname');
let lname = document.querySelector('#lname');
let email = document.querySelector('#email');
let password = document.querySelector('#password');
// INPUT ERRORS
let fnameError = document.querySelector('#fname-error');
let lnameError = document.querySelector('#lname-error');
let emailError = document.querySelector('#email-error');
let passwordError = document.querySelector('#password-error');
function checkForBlank(e) {
e.preventDefault();
console.log(fname.value);
if (fname.value === "") {
fnameError.textContent = 'First Name cannot be empty'
} else {
fnameError.textContent = ''
}
if (lname.value === "") {
lnameError.textContent = 'Last Name cannot be empty'
} else {
lnameError.textContent = ''
}
if (email.value === "") {
emailError.textContent = "Looks like this is not an email"
} else {
emailError.textContent = ''
}
if (password.value === "") {
passwordError.textContent = 'Password cannot be empty'
} else {
passwordError.textContent = ''
}
}
btnCheck.addEventListener('click', checkForBlank);
p.error{
color: red;
font-size: 12px;
padding: 0;
margin: 4px 0 8px 0;
}
<form>
<input type='text' placeholder="First Name" id='fname'>
<p class="error" id="fname-error"></p>
<input type='text' placeholder="Last Name" id='lname'>
<p class="error" id="lname-error"></p>
<input type='text' placeholder="Email Address" id='email'>
<p></p>
<p class="error" id="email-error"></p>
<input type='password' placeholder="Password" id='password'>
<p></p>
<p class="error" id="password-error"></p>
<button id="claim"> check </button>
</form>

How can I verify form passwords match using JavaScript?

I have a basic html form with password and verify password fields. I want to only allow users to continue if passwords match. If passwords do not match, I want there to be a notification to the user.
I think that what I currently have is close, but the JS still doesn't appear to do anything.
HTML
<form class="ajax-form" id="pwreset" method="post" onsubmit="return verifyPassword()" action="/set-password">
<div id="userinput">
<label for="username">Username</label>
<input type="text" id="username" name="username"/><br/>
<label for="new_password">Password</label>
<input type="Password" id="new_password" name="new_password"/><br/>
<label for="verifyPassword">Verify Password</label>
<input type="password" id="verifyPassword" name="verifyPassword"/><br/>
<input type="hidden" id="uuid" name="uuid" value="{{uuid}}"/>
<p><input class="button" type="submit" value="SUBMIT"></p>
</div>
</form>
JS
function verifyPassword() {
let pass1 = document.getElementById("new_password").value;
let pass2 = document.getElementById("verifyPassword").value;
let match = true;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("new_password").style.borderColor = "#ff0000";
document.getElementById("verifyPassword").style.borderColor = "#ff0000";
match = false;
}
else {
alert("Passwords match.");
}
return match;
}
There are some issues that can come from putting the javascript call in the HTML.
In your case, the function was probably defined after the HTML, so the element didn't have access to it.
You can use this instead:
function verifyPassword() {
let pass1 = document.getElementById("new_password").value;
let pass2 = document.getElementById("verifyPassword").value;
let match = true;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("new_password").style.borderColor = "#ff0000";
document.getElementById("verifyPassword").style.borderColor = "#ff0000";
match = false;
}
else {
alert("Passwords match.");
}
return match;
}
document.getElementById('pwreset').onsubmit = verifyPassword;
<form class="ajax-form" id="pwreset" method="post" action="/set-password">
<div id="userinput">
<label for="username">Username</label>
<input type="text" id="username" name="username" /><br/>
<label for="new_password">Password</label>
<input type="Password" id="new_password" name="new_password" /><br/>
<label for="verifyPassword">Verify Password</label>
<input type="password" id="verifyPassword" name="verifyPassword" /><br/>
<input type="hidden" id="uuid" name="uuid" value="{{uuid}}" />
<p><input class="button" type="submit" value="SUBMIT"></p>
</div>
</form>
Here is an example. I created a passwordGroup constructor to centralize the information. This way it's easier to write tests also.
var form = document.forms[0];
var pass1 = form.querySelector('[data-password]');
var pass2 = form.querySelector('[data-password-confirmation]');
var submitButton = form.querySelector('button[type="submit"]');
// PasswordGroup constructor
var PasswordGroup = function () {
this.password = '';
this.passwordConfirmation = '';
};
// method to update the passwords values
PasswordGroup.prototype.setValues = function(data) {
this.password = data.password;
this.passwordConfirmation = data.passwordConfirmation;
};
// method to check the password's equality
PasswordGroup.prototype.match = function() {
return !!(this.password
&& this.passwordConfirmation
&& this.password === this.passwordConfirmation);
};
/*
* Enable/disable the submit button if passwords do not match
*/
function validateSubmit() {
if(passwordGroup.match()) {
submitButton.removeAttribute('disabled');
} else {
submitButton.setAttribute('disabled', 'disabled');
}
}
// passwordGroup instance
var passwordGroup = new PasswordGroup();
// objecto to store the current values
var passwordsValues = {
password: '',
passwordConfirmation: '',
};
// event triggered after enter a new value in the password's field
var onPasswordChange = function(e) {
var target = e.target;
var targetValue = target.value;
if(target.dataset.hasOwnProperty('password')) {
passwordsValues.password = targetValue;
} else if (target.dataset.hasOwnProperty('passwordConfirmation')) {
passwordsValues.passwordConfirmation = targetValue;
}
passwordGroup.setValues(passwordsValues);
validateSubmit();
};
// event attribution
pass1.onkeyup = onPasswordChange;
pass2.onkeyup = onPasswordChange;
input {
display: block;
}
<form action="" name='account'>
<input type="text" placeholder="name" />
<input type="password" data-password placeholder="password"/>
<input type="password" data-password-confirmation placeholder="repeat password"/>
<button type="submit" disabled="disabled">Enviar</button>
</form>
<p data-message></p>

Individual error messages for empty form fields using JavaScript

I need to validate my form using JavaScript because iPhone / Safari do not recognize the required attribute. I want individual error messages to appear below each empty input field.
My code works, but the individual error message does not disappear when the field is filled in. Also, I would like all messages to appear initially, for all empty fields (not one by one). I am very very new to JavaScript, sorry.
My HTML:
<form onsubmit="return validateForm()" method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
<span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" required placeholder="Email">
<span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
<span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>
And my JavaScript:
<script>
function validateForm() {
var x = document.forms["english_registration_form"]["name"].value;
var y = document.forms["english_registration_form"]["email"].value;
var z = document.forms["english_registration_form"]["telephone"].value;
if (x == null || x == "") {
nameError = "Please enter your name";
document.getElementById("name_error").innerHTML = nameError;
return false;
}
else if (y == null || y == "") {
emailError = "Please enter your email";
document.getElementById("email_error").innerHTML = emailError;
return false;
}
else if (z == null || z == "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").innerHTML = telephoneError;
return false;
}
else {return true;}
}
</script>
Thanks for your help.
Here is a solution that displays all relevant errors when the form is first submitted, and removes an error when the user modifies text in the relevant input element.
To get it to display all of the errors on first run, I used if statements instead of if else, and used a flag to determine whether the form should be submitted. To remove the warnings when the input is modified, I bound the onkeyup events of the inputs.
I ended up removing the required attributes on the inputs so that the demonstration will work in a modern browser that supports them.
Live Demo:
document.getElementById("english_registration_form").onsubmit = function () {
var x = document.forms["english_registration_form"]["name"].value;
var y = document.forms["english_registration_form"]["email"].value;
var z = document.forms["english_registration_form"]["telephone"].value;
var submit = true;
if (x == null || x == "") {
nameError = "Please enter your name";
document.getElementById("name_error").innerHTML = nameError;
submit = false;
}
if (y == null || y == "") {
emailError = "Please enter your email";
document.getElementById("email_error").innerHTML = emailError;
submit = false;
}
if (z == null || z == "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").innerHTML = telephoneError;
submit = false;
}
return submit;
}
function removeWarning() {
document.getElementById(this.id + "_error").innerHTML = "";
}
document.getElementById("name").onkeyup = removeWarning;
document.getElementById("email").onkeyup = removeWarning;
document.getElementById("telephone").onkeyup = removeWarning;
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" placeholder="Name"> <span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" placeholder="Email"> <span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" placeholder="Telephone"> <span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>
JSFiddle Version: https://jsfiddle.net/xga2shec/
First of all, we change your function validateForm so it can handle multiple validations.
Then, we create a DOMContentLoaded event handler on the document, and we call the validateForm function, so we validate the field when the page is loaded.
And to finish, we create input event handlers on the inputs, so everytime someone change any data inside them, the form is validated again.
Take a look at the code commented, and see the working version in action!
function validateForm() {
var valid = true; // creates a boolean variable to return if the form's valid
if (!validateField(this, 'name')) // validates the name
valid = false;
if (!validateField(this, 'email')) // validates the email (look that we're not using else if)
valid = false;
if (!validateField(this, 'telephone')) // validates the telephone
valid = false;
return valid; // if all the fields are valid, this variable will be true
}
function validateField(context, fieldName) { // function to dynamically validates a field by its name
var field = document.forms['english_registration_form'][fieldName], // gets the field
msg = 'Please enter your ' + fieldName, // dynamic message
errorField = document.getElementById(fieldName + '_error'); // gets the error field
console.log(context);
// if the context is the form, it's because the Register Now button was clicked, if not, check the caller
if (context instanceof HTMLFormElement || context.id === fieldName)
errorField.innerHTML = (field.value === '') ? msg : '';
return field.value !== ''; // return if the field is fulfilled
}
document.addEventListener('DOMContentLoaded', function() { // when the DOM is ready
// add event handlers when changing the fields' value
document.getElementById('name').addEventListener('input', validateForm);
document.getElementById('email').addEventListener('input', validateForm);
document.getElementById('telephone').addEventListener('input', validateForm);
// add the event handler for the submit event
document.getElementById('english_registration_form').addEventListener('submit', validateForm);
});
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
<span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" required placeholder="Email">
<span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
<span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>
you have to use style.display="none" to hide error
and style.display="block" to show error
<script>
function validateForm() {
var x = document.forms["english_registration_form"]["name"].value;
var y = document.forms["english_registration_form"]["email"].value;
var z = document.forms["english_registration_form"]["telephone"].value;
if (x == null || x == "") {
nameError = "Please enter your name";
document.getElementById("name_error").style.display="block";
document.getElementById("name_error").innerHTML = nameError;
return false;
}
else if (x != null || x != "") {
nameError = "Please enter your name";
document.getElementById("name_error").style.display="none";
return false;
}
if (y == null || y == "") {
emailError = "Please enter your email";
document.getElementById("email_error").style.display="block";
document.getElementById("email_error").innerHTML = emailError;
return false;
}
else if (y != null || y != "") {
emailError = "Please enter your email";
document.getElementById("email_error").style.display="none";
return false;
}
if (z == null || z == "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").style.display="block";
document.getElementById("telephone_error").innerHTML = telephoneError;
return false;
}
else if (z != null || z != "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").style.display="none";
return false;
}
else {return true;}
}
</script>
function validateForm() {
var valid = true; // creates a boolean variable to return if the form's valid
if (!validateField(this, 'name')) // validates the name
valid = false;
if (!validateField(this, 'email')) // validates the email (look that we're not using else if)
valid = false;
if (!validateField(this, 'telephone')) // validates the telephone
valid = false;
return valid; // if all the fields are valid, this variable will be true
}
function validateField(context, fieldName) { // function to dynamically validates a field by its name
var field = document.forms['english_registration_form'][fieldName], // gets the field
msg = 'Please enter your ' + fieldName, // dynamic message
errorField = document.getElementById(fieldName + '_error'); // gets the error field
console.log(context);
// if the context is the form, it's because the Register Now button was clicked, if not, check the caller
if (context instanceof HTMLFormElement || context.id === fieldName)
errorField.innerHTML = (field.value === '') ? msg : '';
return field.value !== ''; // return if the field is fulfilled
}
document.addEventListener('DOMContentLoaded', function() { // when the DOM is ready
// add event handlers when changing the fields' value
document.getElementById('name').addEventListener('input', validateForm);
document.getElementById('email').addEventListener('input', validateForm);
document.getElementById('telephone').addEventListener('input', validateForm);
// add the event handler for the submit event
document.getElementById('english_registration_form').addEventListener('submit', validateForm);
});
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
<span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" required placeholder="Email">
<span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
<span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>

Javascript not working in html file

I have written code for a basic registration page to run on my webserver but javascript doesn't seem to be working in the html file. I do a form post with a javascript function to find errors but it seems to be completely ignoring the javascript code when I test it. Is there a problem with my javascript code or in the html code? My code is shown below.
<script type="text/javascript" language="Javascript">
function checkPasswordMatch(){
var password = document.getElementById("pass1").value;
var password2 = document.getElementById("pass2").value;
if(password != password2){
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords do not match!";}
else{
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords match.";}
}
// $(document).ready(function(){
// $("#pass2").keyup(checkPasswordMatch);
// })
function Error() {
var user = document.getElementById("user").value;
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
var email = document.getElementById("email").value;
if(user=""){
document.form1.username.focus();
document.getElementById("usernameerror").innerHTML = "Enter username.";
return false;
}
if(pass1=""){
document.form1.password1.focus();
document.getElementById("passworderror1").innerHTML = "Enter password.";
return false;
}
if(pass2=""){
document.form1.password2.focus();
document.getElementById("passworderror2").innerHTML = "Enter password.";
return false;
}
if(email=""){
document.form1.useremail.focus();
document.getElementById("emailerror").innerHTML = "Enter email";
return false;
}
}
</script>
</head>
<body>
<div id="link">
Home
<a align="right" href="signin">Sign-in</a>
</div>
<div id="header">
<center><h1><i>IMGCAPTURE</i></h1></center>
</div>
<div id="create">
<center><h2>Create Your Account</h2></center>
<form name="form1" action="account" onsubmit="return Error()" method="POST">
<div id="username"><center><h3>Enter Username: <input type="text" name="username" id="user" cols="15" rows="1"></input></h3></center></div>
<div id="usernameerror"></div>
<div id="password"><center><h3>Enter Password: <input type="password" name="password1" id="pass1" cols="15" rows="1"></input></h3></center></div>
<div id="passworderror1"></div>
<div id="confirmpassword"><center><h3>Re-Enter Password: <input type="password" name="password2" id="pass2" onChange="checkPasswordMatch()" cols="15" rows="1"></input></h3></center></div>
<div id="passworderror2"></div>
<div class="registrationFormAlert" id="divcheckpasswordmatch"></div>
<center><h3>Enter Email: <input type="email" name="useremail" id="email" cols="15" rows="1">
</input></h3></center>
<div id="emailerror"></div>
<center><input type="submit" value="Create Account" onclick="Error()"></input></center>
</form>
</div>
</body>
</html>
It may be that you are not calling the functions you are creating. So since you are not calling those functions with arguments, nothing inside them is going to happen. Let me know if this fixes it.
Also, stylistically you would want the Javascript code at the end of the HTML file.
Instead of binding your input name="password2" to the function by the onChange-tag, try binding it like this:
$(document).on('change', 'input[name="checkPasswordMatch"]', checkPasswordMatch);
function checkPasswordMatch() {
...
}
And in your HTML, remove the onChange tag:
<div id="confirmpassword">
<center>
<h3>
Re-Enter Password: <input type="password" name="password2" id="pass2" cols="15" rows="1"></input>
</h3>
</center></div>
It seems you've forgotten to include jQuery. If you use pure JS, it works :
<script type="text/javascript">
function checkPasswordMatch() {
var password = document.getElementById("pass1").value;
var password2 = document.getElementById("pass2").value;
if (password != password2) {
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords do not match!";
} else {
document.getElementById("divcheckpasswordmatch").innerHTML = "Passwords match.";
}
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("pass2").addEventListener('keyup', checkPasswordMatch);
});
function Error() {
var user = document.getElementById("user").value;
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
var email = document.getElementById("email").value;
if (user = "") {
document.form1.username.focus();
document.getElementById("usernameerror").innerHTML = "Enter username.";
return false;
}
if (pass1 = "") {
document.form1.password1.focus();
document.getElementById("passworderror1").innerHTML = "Enter password.";
return false;
}
if (pass2 = "") {
document.form1.password2.focus();
document.getElementById("passworderror2").innerHTML = "Enter password.";
return false;
}
if (email = "") {
document.form1.useremail.focus();
document.getElementById("emailerror").innerHTML = "Enter email";
return false;
}
}
</script>
You probably want to use == or === in your if statements. You're assigning user, etc. to an empty string in your if conditionals.
if(user == ""){
document.form1.username.focus();
document.getElementById("usernameerror").innerHTML = "Enter username.";
return false;
}

Javascript text field validation

I am having difficulty validating a form in javascript. I'm currently checking just a text field and it doesn't work. My code is as followed:
index.html:
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>
Validation Form
</title>
<script type = "text/javascript" src ="vForm.js">
</script>
</head>
<body>
<form id = "myForm" action ="">
First name: <input type="text" name="fname"></br>
Last name: <input type="text" name="lname"></br>
Password: <input type="password" name="pass1"></br>
Re-enter password: <input type="password" name="pass2"></br>
Email: <input type="text" name="email"></br>
Phone: <input type="text" name="phone"></br>
Address: <input type="text" name="add"></br>
Date: <input type="date" name="date"></br>
Time: <input type="time" name="time"></br>
<input type="reset" name="reset">
<input type="submit" name="submit">
</form>
<script type = "text/javascript" src ="vFormRun.js">
</script>
</body>
</html>
vForm.js:
function validateForm()
{
var fname = document.getElementById("fname");
var lname = document.getElementById("lname");
var pass1 = document.getElementById("pass1");
var pass2 = document.getElementById("pass2");
var email = document.getElementById("email");
if(fname == "")
{
alert("Please enter first name")
return false;
}
else
{
return true;
}
}
vFormRun.js:
document.getElementById("myForm").onsubmit = validateForm;
You need to give .value to each of it. And also, give an id of the same name.
function validateForm()
{
var fname = document.getElementById("fname");
var lname = document.getElementById("lname");
var pass1 = document.getElementById("pass1");
var pass2 = document.getElementById("pass2");
var email = document.getElementById("email");
if(fname.value == "")
{
alert("Please enter first name")
return false;
}
else
{
return true;
}
}
document.getElementById("fname");
That will only work if you have an element with an ID of fname, which you do not.
You can set the ID attribute to an element like so:
<input type="text" name="fname" id="fname">
Alternatively, you can reference the form elements like this:
var fname = document.forms["myForm"]["fname"]
Then you want to get it's value property when comparing.
fname.value
The <br> tag is self closing, so it should be <br /> instead of </br>
Here is the solution...
function validateForm(form) {
var fname = form.fname,
lname = form.lname,
pass1 = form.pass1,
pass2 = form.pass2,
email = form.email;
if(fname && fname.value === "") {
alert("Please enter first name");
document.getElementById('result').innerHTML = 'Invalid';
return false;
}
document.getElementById('result').innerHTML = 'Passed';
return true;
}
<form id="myForm" action="" onsubmit="validateForm(this)">
First name: <input type="text" name="fname"><br/>
Last name: <input type="text" name="lname"><br/>
Password: <input type="password" name="pass1"><br/>
Re-enter password: <input type="password" name="pass2"><br/>
Email: <input type="text" name="email"><br/>
Phone: <input type="text" name="phone"><br/>
Address: <input type="text" name="add"><br/>
Date: <input type="date" name="date"><br/>
Time: <input type="time" name="time"><br/>
<input type="reset" name="reset">
<input type="submit" name="submit">
<p id="result">
</p>
</form>
There were a few issues here that I corrected.
I changed all of the var declarations to use one var declaration. This is a best practice.
In the if statement I added a check for the variable fname to make sure it exists and is not null (prevents a null reference error).
In the if statement you need to check the value attribute of the filed, not the field itself. In your old code if it is blank or not the field should be there and would have always returned true.
I changed the comparison to use === instead of ==. When using ==, if the value is "false" or 0 it will return true. See "Difference between == and === in JavaScript".
You were missing a semicolon at the end of the alert statement.
If the body of the if ends with a return then you do not need an else block. Cuts down the amount of code (downloads faster) and makes it easier to read.

Categories

Resources