I have a script here that is supposed to run when triggered. However, it will only work if the variable passwd is not used in my if else statements.
NEWLY UPDATED JS:
function validateForm() {
var name = document.forms["myForm"]["name"].value;
var phone = document.forms["myForm"]["phone"].value;
var email = document.forms["myForm"]["email"].value;
var add = document.forms["myForm"]["address"].value;
var passwd = document.forms["myForm"]["password"].value;
var matchesCount = email.split("#").length - 1;
var matchesCount2 = email.split(".").length - 1;
var error = "";
if (!name || !phone || !email || !add || !passwd) {
error+="All must be filled out \n"
if(phone.search(/^[0-9]*$/) == -1 || phone.length != 8){
error+="- Phone number can only contain digits \n";}
if(passwd.search(/^[0-9a-zA-Z]*$/) == -1){
error+="- Password needs to be alphanumeric \n";
}
if(passwd.length <8 || passwd.length > 16){
error+="- Password contain only 8-16 digits \n";
}
if(matchesCount > 1 || matchesCount2 < 1){
error+="- Please enter a valid email \n";
}
alert(error);
return false;
}
}
HTML
<div id="newaccount">
<table id="tablenewuser">
<form name="myForm" action="ControllerServlet" onsubmit="return validateForm()" method="post">
<tr>
<td class="newusertd">Name:<span class="price">*</span></td>
<td class="newusertd"><input style="color: black;" type="text" name="name" class="Btn"></td>
</tr>
<tr>
<td class="newusertd">Contact Number:<span class="price">*</span></td>
<td class="newusertd"><input style="color: black;" type="text" name="phone" placeholder="98989898"class="Btn"></td>
</tr>
<tr>
<td class="newusertd">Email:<span class="price">*<br></span></td>
<td class="newusertd"><input style="color: black;" type="text" name="email" placeholder="xxx#hello.com" class="Btn"></td>
</tr>
<tr>
<td class="newusertd">Address:<span class="price">*</span></td>
<td class="newusertd"><input style="color: black;" type="text" name="address" class="Btn"></td>
</tr>
<tr>
<td class="newusertd">Password:<span class="price">*</span><br>(8-16 Characters with<br>one UPPERCASE & numbers)</td>
<td class="newusertd"><input style="color: black;" type="password" name="password" class="Btn">
</tr>
<tr>
<td class="newusertd"></td>
<td class="newusertd">
<input style="color: black;" type="submit" value="Create Account" class="Btn"/></td>
</tr>
</form>
</table>
</div>
(Sorry for the mess!)
EDIT: The script works but the the password is not working as it should be. Please see the comments
Quick glance shows at least 2 problems with that area:
passwd could be null and pass through the outer if condition. Attempting length on it would cause an error
You may want to wrap the inner conditionals in an else block
if (name == null || name == "" || phone == null || phone == "" || email == null || email == "" || add == null || add == ""
|| passwd == null || passwd == "") {
error+="All must be filled out \n";
} else {
// other conditions
}
if (error) alert(error);
In JS, it's passwd.length not length()
You should use the JS console to verify what errors are appearing.
I see the problem, .length is a property, not a method. Your length check should be:
if (passwd.length >= 8 && passwd.length <= 16) {
error += "- Only 8-16 digits \n";
}
One more note, foo == null || foo == "" can be simplified to !foo as null and "" are both falsy values in JS.
Im not expert but i recommend you evaluate mail field with regex (/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/) and i created a separated function for validate each of the values in the form for add a text error, then another validation who evaluate if all the fiels pass the evaluation, like yours but i made it liek that: if(validateName(nameVar) && validateEmail(emailVar) this is all the code that i made, that validate a correct form mail, a name with alphabetical form and phone without null value:
function validateName(nameVar) {
var nameReg = /^[a-zA-Z'.\s]{1,40}$/;
return nameReg.test(nameVar);
}
function validateEmail(emailVar) {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test(emailVar);
}
function email() {
var nameVar = $('#name').val();
var emailVar = $('#email').val();
var phoneVar = $('#phone').val();
var messageVar = $('#message').val();
if(!validateName(nameVar) ) {
console.log("dentro");
$('#nameError').text("Por favor ingresa un nombre valido");
}else{
$('#nameError').text("");
}
if(!validateEmail(emailVar) || emailVar == "") {
$('#emailError').text("Por favor ingresa un correo valido");
}else{
$('#emailError').text("");
}
if(phoneVar == "") {
$('#phoneError').text("Por favor ingresa un número telefonico");
}else{
$('#phoneError').text("");
}
if(validateName(nameVar) && validateEmail(emailVar) && emailVar != "" && phoneVar != ""){
var data = {};
data.name = nameVar;
data.email = emailVar;
data.phone = phoneVar;
data.message = messageVar;
//here your validate code with array of values ready for doing something
}
};
and this is the html code:
<h4 class="title-yellow contacto" id="title-yellow">Envianos un mensaje</h4>
<div class="row"> </div>
<div class="row">
<div class="col-md-6 form-group">
<input class="form-control" id="name" name="nombre" placeholder="Nombre" type="text" required >
</div>
<div class="col-md-6 form-group">
<input class="form-control" id="email" name="email" placeholder="Email" type="email" required >
</div>
</div>
<div class="row">
<div class="col-md-12 form-group">
<input class="form-control" id="phone" name="telefono" placeholder="Teléfono" type="tel" required >
</div>
</div>
<textarea class="form-control" id="message" name="mensaje" placeholder="Mensaje" rows="4">
</textarea>
<br>
<div class="row">
<div class="col-md-12 form-group">
<button class="email nohover pull-right" id="mail" onclick="email()">ENVIAR</button>
<p id="demo"></p>
<div id="nameError"></div>
<div id="emailError"></div>
<div id="phoneError"></div>
<div id="ajaxMessage"></div>
</div>
</div>
Related
<!DOCTYPE html>
<html>
<body>
<div class="needContent">
<label for="Password">Password</label>
<span class="red-star">∗</span>
<input type="password" name="Password" id="Password" required="required" onkeyup="starShow()" pattern="^(?=.*\[a-z\])(?=.*\[A-Z\])(?=.*\d)\[a-zA-Z\d\]{8,}$" onchange="check()">
</div>
<div class="needContent">
<label for="Retype_Password">Retype Password</label>
<span class="red-star">∗</span>
<input type="password" name="Retype_Password" id="Retype_Password" pattern="^(?=.*\[a-z\])(?=.*\[A-Z\])(?=.*\d)\[a-zA-Z\d\]{8,}$" required="required" onkeyup="starShow()" onchange="check()">
<p id="status"></p>
<div id="phoneNumber" class="needContent">
<label for="Phone_Number" >Phone Number</label>
<span class="red-star">∗</span>
<input type="tel" name="Phone_Number" id="Phone_Number"
required="required" onchange="Error()" placeholder="999-999-9999"
onkeyup="starShow()" >
<p id="showEorror"></p>
</div>
</div>
<script>
function Error() {
var phn = document.getElementById("Phone_Number").value;
if(phn[3]!="-" && phn[7] != "-" ) {
document.getElementById("showEorror").innerHTML="<span>X</span> The area code of phone number 999-999-9999 can't be all zeros.";
}else if(phn[0] == 0 || phn[1] == 0 && phn[2] == 0){
document.getElementById("showEorror").innerHTML="<span>X</span> The area code of phone number 999-999-9999 can't be all zeros.";
} else {
document.getElementById("showEorrr").style.display = "none";
}
}
function check() {
var pass1 = document.getElementById("Password").value;
var pass2 = document.getElementById("Retype_Password").value;
if (pass1 != "" && pass2 != "") {
if (pass1 != pass2) {
document.getElementById("status").innerHTML = "<span>X</span> Doesn't Match.";
}
}
}
</script>
</body>
</html>
So I am working on my school project and I am trying to display the error "Doesn't Match" same as the one for the phone but I don't know what I am doing wrong. I have attached a screen shot of my output.
You're not resetting the #status text after the password gets properly entered. Try this instead:
if (pass1 != "" && pass2 != "") {
if (pass1 != pass2) {
document.getElementById("status").innerHTML = "<span>X</span> Doesn't Match.";
} else document.getElementById("status").textContent = 'ok';
}
For the phone section, you have a typo or two: "showEorror" vs "showEorrr", which means that, again, the error text does not go away. I recommend using showError or showPhoneError instead.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
How to print error message under respective input field if left empty and error message must be removed when filled, how to proceed further i have not used javascript for validation earlier.
script code
function validateForm() {
var a = document.forms["student_reg"]["name"].value;
if (a == null || a == "") {
alert("Name must be filled out");
return false;
}
var b = document.forms["student_reg"]["email"].value;
if (b == null || b == "") {
alert("Email must be filled out");
return false;
}
var c = document.forms["student_reg"]["username"].value;
if (c == null || c == "") {
alert("Username must be filled out");
return false;
}
var d = document.forms["student_reg"]["password"].value;
if (d == null || d == "") {
alert("Password must be filled out");
return false;
}
var e = document.forms["student_reg"]["roll_no"].value;
if (e == null || e == "") {
alert("Roll no must be filled out");
return false;
}
}
html code is here
<body>
Login
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="" >
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="" >
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="" >
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="" >
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="" >
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
</body>
You can try this code:
It will check errors and returns at last after displaying all error messages if any.
function validateForm() {
var error = 0;
var a = document.forms["student_reg"]["name"].value;
document.getElementById('name_error').innerHTML = '';
if (a == null || a == "") {
// alert("Name must be filled out");
error++;
document.getElementById('name_error').innerHTML = 'Name must be filled out';
}
var b = document.forms["student_reg"]["email"].value;
document.getElementById('email_error').innerHTML = '';
if (b == null || b == "") {
// alert("Email must be filled out");
error++;
document.getElementById('email_error').innerHTML = 'Email must be filled out';
}
var c = document.forms["student_reg"]["username"].value;
document.getElementById('username_error').innerHTML = '';
if (c == null || c == "") {
// alert("Username must be filled out");
error++;
document.getElementById('username_error').innerHTML = 'Username must be filled out';
}
var d = document.forms["student_reg"]["password"].value;
document.getElementById('password_error').innerHTML = '';
if (d == null || d == "") {
// alert("Password must be filled out");
error++;
document.getElementById('password_error').innerHTML = 'Password must be filled out';
}
var e = document.forms["student_reg"]["roll_no"].value;
document.getElementById('roll_no_error').innerHTML = '';
if (e == null || e == "") {
// alert("Roll no must be filled out");
error++;
document.getElementById('roll_no_error').innerHTML = 'Roll no must be filled out';
}
if(error>0) {
return false;
}
return true;
}
Keep all the name attributes in array and validate in loop. As your ID is related to name attribute, concatenate the name with _error to get the ID of the error placeholder.
function validateForm() {
var names = ['name', 'email', 'username', 'password', 'roll_no'];
var errorCount = 0;
names.forEach(function(el) {
var val = document.forms["student_reg"][el].value;
if (val == null || val == "") {
document.getElementById(el + '_error').textContent = el.toUpperCase().replace('_', ' ') + " must be filled out";
++errorCount;
}
});
if (errorCount) return false;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"><p id="name_error"></p></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"><p id="email_error"></p></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"><p id="username_error"></p></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"><p id="password_error"></p></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"><p id="roll_no_error"></p></span>
<br/>
<br/>
<br/>
<input type="submit" name="submit" value="submit">
</form>
You can iterate through all elements of the form student_reg to validate email and required and print error message under respective input field if no value was set:
const validateForm = () => {
const form = document.forms['student_reg'],
inputs = [...form.getElementsByTagName('input')],
errors = [...form.getElementsByClassName('error')],
regex = /\S+#\S+\.\S+/,
setErrorMsg = (str, msg) => `${str.replace('_', ' ')} ${msg}`
let countErrors = 0
inputs.forEach((input, index) => {
// clear all errors
(errors[index] || '').innerHTML = ''
// validate email
if (input.name === 'email' && !regex.test(input.value)) {
errors[index].innerText = setErrorMsg(input.name, 'should be valid')
countErrors++
}
// validate required
if (!input.value) {
errors[index].innerText = setErrorMsg(input.name, 'field is required')
countErrors++
}
})
return countErrors === 0
}
p {
font-size: 13px;
margin: 4px 0 0;
}
.error {
font-size: 12px;
padding: 6px 0 4px;
color: red;
display: block
}
.error:first-letter {
text-transform: uppercase
}
button {
margin-top: 8px;
font-size: 16px;
}
<form name="student_reg" method="POST" action="" onsubmit="return validateForm()">
<p>NAME:</p>
<input type="text" name="name" value="">
<span class="error"></span>
<p>EMAIL:</p>
<input type="text" name="email" value="">
<span class="error"></span>
<p>USERNAME:</p>
<input type="text" name="username" value="">
<span class="error"></span>
<p>PASSWORD:</p>
<input type="password" name="password" value="">
<span class="error"></span>
<p>ROLL NO:</p>
<input type="number" name="roll_no" value="">
<span class="error"></span>
<button>Submit</button>
</form>
simple form It hold the Span for the Error msg.The span Id is very important here.you need to make color for errors using css
<form id="loginform" name="loginform" action="" method="post">
<label>Name</label>
<input type="text" name="username" />
<p></p>
<span id="usernameError"></span>
<p></p>
<label>Pwd</label>
<input type="password" name="password" />
<p></p>
<span id="passwordError"></span>
<p></p>
<input type="submit" value="Submit" />
</form>
script
<script type="application/javascript">
window.onload = function(){
function handleinput(){
if(document.loginform.username.value == ""){
document.getElementById("usernameError").innerHTML = "You must enter a username";
return false;
}
if(document.loginform.password.value == ""){
document.getElementById("passwordError").innerHTML = "You must enter a password";
return false;
}
}
document.getElementById("loginform").onsubmit = handleinput;
}
</script>
Not sure why this isn't working.
<!DOCTYPE html>
<html>
<head>
<title>Player 1</title>
<link rel="stylesheet" type="text/css" href="playerOne.css">
</head>
<body>
<div id="heading">
<h>Player 1</h>
</div>
<form name="playerInfo" onsubmit="return validate()" method="post">
<hr>
<fieldset>
<legend>Personal information:</legend>
<label id="inPID">Player ID:</label>
<br>
<input type="text" name="playerid" class="input" id="id" placeholder="Player ID" autofocus >
<br>
<br>
<label id="inFN">First name:</label>
<br>
<input type="text" name="firstname" class="input" id="fname" placeholder="First name" >
<br>
<br>
<label id="inLN">Last name:</label>
<br>
<input type="text" name="lastname" class="input" id="sname" placeholder="Last name" >
<br>
<br>
<label id="inEA">Email address:</label>
<br>
<input type="text" name="email" class="input" id="email" placeholder="Email address">
<br>
<br>
<label id="inPW">Password:</label>
<br>
<input type="password" name="password" class="input" id="pass" >
<br>
<br>
<input type="submit" value="Validate" class="input" id="validate" >
</fieldset>
<hr>
</form>
<div id="error"></div>
<script>
function testVal(){
return false;
}
function validate() {
var message;
var test = true;
message = document.getElementById("error");
message.innerHTML += "";
var x = document.getElementById("id");
if(x.value == ""|| x.value == null||x.value== "Player ID") {
x.style.backgroundColor = "#FF0000";
message.innerHTML += "Player ID is missing\n";
test = false;
}else{
}
var x = document.getElementById("fname");
if(x.value == ""){
x.style.borderColor = "#FF0000";
message.innerHTML += "First name is missing\n";
test = false;
}else{
}
var x = document.getElementById("sname");
if(x.value == "") {
x.style.borderColor ="#FF0000";
message.innerHTML += "Surname is missing\n";
test = false;
}else{
}
var x = document.getElementById("email");
if(x.value == "") {
x.style.borderColor = "#FF0000";
message.innerHTML += "Email is missing\n";
test = false;
}else{
}
var x = document.getElementById("pass");
if(x.value == ""){
x.style.borderColor = "#FF0000";
message.innerHTML += "Password is missing\n";
test = false;
}else{
}
return test;
}
</script>
</body>
So it should change the color of the borders to red if the input is incorrect( or empty), and inform the user in a div. For some reason, the code is always submitting without recognizing the errors. Also I'm a beginner at JavaScript (and html) so if anyone has any input on improving this code it would be appreciated.
EDIT: Apologies. I uploaded the wrong version of the code the testval function was only there to check if the onsubmit was working correctly, and the validate function is now called onsubmit, which is where/when it should be but is not working.
EDIT 2: Thank you for your help on the format and correct tag use. I have edited it as to your recommendations, however the actual validating (function) is still not working, despite the inclusion of quotation marks.
references:
http://www.w3schools.com/js/js_validation.asp
http://www.tutorialspoint.com/javascript/javascript_form_validations.htm
Look at your console errors.
First is a typo in testVal - "retrun" instead of "return".
Next up, strings need to be quoted so x.style.borderColor = #FF0000; needs to be x.style.borderColor = "#FF0000";
Beyond that, you don't actually seem to be calling validate() in the code provided. Also, look into using the placeholder attribute for input elements, or - possibly more appropriate - the label element, rather than your approach of putting the label inside the value of each input.
You gave the same name x for JavaScript variables. I also fixed your form a little.
Some suggestions:
The \n in a.innerHTML += "Some string\n" doesn't work. Use "<br />" instead
Different names for different variables please
Use the placeholder attribute instead of value to suggest the user
Use the message variable to hold the error message instead of setting the innerHtml directly because Javascript uses Pass By Value (see reference)
When you get more acquainted with Javascript, you would want to learn jQuery. It provides a great API for easier time coding as well as make Html traversal, event handling and Ajax much simpler. http://www.w3schools.com/jquery/default.asp is a great place to learn jQuery.
Fixed Javascript and Html:
function validate() {
var message = "";
var test = true;
var id = document.getElementById("id");
if (id.value == "" || id.value == null) {
id.style.backgroundColor = "#FF0000";
message += "Player ID is missing<br />";
test = false;
} else {
}
var fname = document.getElementById("fname");
if (fname.value == "" || fname.value == null) {
fname.style.borderColor = "#FF0000";
message += "First name is missing<br />";
test = false;
} else {
}
var sname = document.getElementById("sname");
if (sname.value == "" || sname.value == null) {
sname.style.borderColor = "#FF0000";
message += "Surname is missing<br />";
test = false;
} else {
}
var email = document.getElementById("email");
if (email.value == "" || email.value == null) {
email.style.borderColor = "#FF0000";
message += "Email is missing<br />";
test = false;
} else {
}
var x = document.getElementById("pass");
if (x.value == "" || x.value == null) {
x.style.borderColor = "#FF0000";
message += "Password is missing<br />";
test = false;
} else {
}
if (test == true) {
document.alert("OK");
// document.getElementById("frmPlay").submit();
} else {
document.getElementById("error").innerHtml = message;
}
}
<form name="playerInfo" onsubmit="validate()" method="post" id="frmPlay">
<hr>
<fieldset>
<legend>Personal information:</legend>
<label>Player ID:</label>
<br>
<input type="text" name="playerid" class="input" id="id" placeholder="Player ID" autofocus>
<br>
<br>
<label>First name:</label>
<br>
<input type="text" name="firstname" class="input" id="fname" placeholder="First name">
<br>
<br>
<label>Last name:</label>
<br>
<input type="text" name="lastname" class="input" id="sname" placeholder="Last name">
<br>
<br>
<label>Email address:</label>
<br>
<input type="text" name="email" class="input" id="email" placeholder="Email address">
<br>
<br>
<label>Password:</label>
<br>
<input type="password" name="password" class="input" id="pass">
<br>
<br>
<input type="submit" value="Validate" class="input" id="validate">
</fieldset>
<hr>
</form>
<div id="error"></div>
I have the following validation code for a simple form. I am able to perform basic validation but the form still gets posted even if the data is wrong and an alert is generated. How can I stop that from happening?
JS CODE
function validate(){
validateForm();
}
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["pname"].value;
var email = document.forms["myForm"]["email"].value;
var phone = document.forms["myForm"]["phone"].value;
var date = document.forms["myForm"]["date"].value;
var month = document.forms["myForm"]["month"].value;
var year = document.forms["myForm"]["year"].value;
window.load = function() {
var myForm = document.getElementById('myForm');
myForm.onsubmit = function(e) {
return validateForm(); // will be false if the form is invalid
}
}
if (x == null || x == "") {
alert("Name must be filled out");
return false;}
else if (y == null || y == "") {
alert("Address must be filled out");
return false;
}
else if(email == '' || email.indexOf('#') == -1 || email.indexOf('.') == -1)
{
alert("Insert Valid Email Address");
return false;
}
else if(phone == ''|| phone <1000000000 || phone >9999999999){
alert("Enter valid phone number");
return false;
}else if(date =='' || date<01 || date >31){
alert("Enter valid date ");
return false;
}else if(month =='' || month<1 || month >12){
alert("Enter valid month ");
return false;
}else if(year =='' || year<1800 || year >2015){
alert("Enter valid year ");
return false;
}
}
Form
<form name="myForm" action="http://www.randyconnolly.com/tests/process.php" onsubmit="return validate()" method="post">
<table width="30%" border="0" align="center" cellpadding="10" cellspacing="20">
<tr>
<td width="20%"> <span style="font-size: 22px">Name:</span><br>
<br /></td>
<td width="80%"><input type="text" name="fname" required /></td>
</tr>
<tr>
<td><span style="font-size: 22px">Picture Name: <br>
<br></span></td>
<td><input type="text" name="pname" required /></td>
</tr>
<tr>
<td><span style="font-size: 22px">Email:</span> <br>
<br></td>
<td><input type="text" name="email" required /></td>
</tr>
<tr>
<td><span style="font-size: 22px">Phone:</span> <br>
<br></td>
<td><input type="number" name="phone" required /></td>
</tr>
<tr>
<td><span style="font-size: 22px">Date(mm/dd/yyyy):</span></td>
<td><input type="text" name="month" size="2" required />
/
<input type="text" name="date" size="2" required />
/
<input type="text" name="year" size="4" required /></td>
</tr>
<tr>
<td><span style="font-size: 22px">Artwork</span></td>
<td><input type="file" accept="image/gif" name="pic" ></td>
</tr>
</table>
<br><br>
<input class="button-0" type="submit" value="Submit" />
<br>
</form>
You have several issues with your code.
Your validation function needs to return false to prevent the form submission.
You are registering the window.onload handler inside of the validateForm function. Since, the the time the validateForm function is called, the form is already being submitted.
The handler in your markup is validate. Your validate method doesn't return anything so submission won't be prevented by that either.
The easiest way to fix everything would to be to remove the window.onload handler from your code altogether. You could then change validate to:
function validate() {
return validateForm();
}
And submission should be prevented properly.
I got it working. Instead of calling validate() and in that calling validateForm() I directly called validateForm() at the onsubmit. Thanks for the help.
I am new to javascript and I am attempting to create a simple form validation. When I hit the submit button nothing happens. I have been looking at examples for a while and I cannot seem to figure out where I am going wrong. Any suggestions:
HTML:
<form name="myForm" class="appnitro" onsubmit="return validateForm()" action="mysql_connection.php" method="post">
<div class="form_description">
<h2>Patient Record</h2>
<p></p>
</div>
<ul>
<li id="li_1">
<label class="description" for="element_1"> Name</label>
<span>
<td width="68%"><input size="15" maxlength="30" class="input" type="text" name="Fname" id="Fname"></td>
<label>First</label>
</span>
<span>
<td width="68%"><input size="15" maxlength="30" class="input" type="text" name="Lname" id="Lname"></td>
<label>Last</label>
</span>
<li class="buttons">
<label class="description" for="element_1"> Gender</label>
<span>
<tr>
<select name="Gender">
</tr>
</span>
<option value="Select">Select</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<li class="buttons">
<label class="description" for="element_3"> Age</label>
<span>
<tr>
<select name="Age">
</tr>
</span>
<script type="text/javascript">
listAge()
</script>
</select>
<li class="buttons">
<label class="description" for="element_3"> Phone Number</label>
<span>
<td width="68%"><input size="25" maxlength="50" class="input" type="text" name="Phone" id="Phone"></td>
</span>
<li class="buttons">
<label class="description" for="element_3"> Email ID</label>
<span>
<td width="68%"><input size="25" maxlength="50" class="input" type="text" name="Email" id="Email"></td>
</span>
<li class="buttons">
<label class="description" for="element_3"> Address</label>
<span>
<td><textarea cols="25" rows="3" class="input" name="Address" id="Address"></textarea></td>
</span>
<li class="buttons">
<label class="description" for="element_3"> Reason For Visit</label>
<span>
<td><textarea cols="25" rows="3" class="input" name="Reason" id="Reason"></textarea></td>
</span>
<li class="buttons">
<label class="description" for="element_3"> Attending Doctor</label>
<span>
<td width="68%"><input size="25" maxlength="50" class="input" type="text" name="Doctor" id="Doctor"></td>
</span>
<li class="buttons">
<input type="submit" value="Submit" />
<input type="reset" value="Reset">
</li>
</ul>
</form>
Javascript:
<script>
function validateForm() {
var Fname = document.forms["myForm"]["Fname"].value;
var Lname = document.forms["myForm"]["Lname"].value;
var Phone = document.forms["myForm"]["Phone"].value;
var Address = document.forms["myForm"]["Address"].value;
var Reason = document.forms["myForm"]["Reason"].value;
var Doctor = document.forms["myForm"]["Doctor"].value;
var email = document.forms["myForm"]["email"].value;
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (Fname == null || Fname == "") {
alert("First name must be filled out");
return false;
}
if (Lname == null || Lname == "") {
alert("Last name must be filled out");
return false;
}
if (Phone == null || Phone == "") {
alert("Phone Number must be filled out");
return false;
}
if (Address == null || Address == "") {
alert("Address must be filled out");
return false;
}
if (Reason == null || Reason == "") {
alert("Reason for Visit must be filled out");
return false;
}
if (Doctor == null || Doctor == "") {
alert("Attending Doctor must be filled out");
return false;
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
}
}
function listAge() {
var i = 1;
for (i = 1; i <= 100; i++) {
document.write("<option value=" + i + ">" + i + "</option>");
}
}
</script>
Your HTML is hideously invalid. Odds are that the browser is trying to perform error recovery and doing things like moving the <form> element outside the table (assuming there is a table, it doesn't show up in your code but you have table data cells in it) so that the submit button is no longer inside it and does not try to submit the form. (This is a known problem with trying to interleave forms a table rows).
Use a validator to find your errors then fix them.
#Quentin is right, you need to clean your HTML code and javascript code.
But you have an error in your Javascript. You need to write a capital E for the Email field. It is case sensitive.
Try with this :
var email = document.forms["myForm"]["Email"].value;
Why not directly use the ID attribute of the element as if you put an ID inside any element it is always preferred to keep it unique. So you can use document.getElementById("ID").value; to get the value of an individual element. Like this :
var firstName = document.getElementById("firstNameTextBox").value;
if(firstName == ''){
message.innerHTML = "First Name is required";
}
I have a demo that you should try.
Demo
Add this JavaScript code and it should word
function validateForm() {
var Fname = document.forms["myForm"]["Fname"].value;
var Lname = document.forms["myForm"]["Lname"].value;
if (Fname == null || Fname == "") {
alert("First name must be filled out");
return false;
}
if (Lname == null || Lname == "") {
alert("Last name must be filled out");
return false;
}
if (Phone == null || Phone == "") {
alert("Phone Number must be filled out");
return false;
}
if (Address == null || Address == "") {
alert("Address must be filled out");
return false;
}
if (Reason == null || Reason == "") {
alert("Reason for Visit must be filled out");
return false;
}
if (Doctor == null || Doctor == "") {
alert("Attending Doctor must be filled out");
return false;
}
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
}
}
function listAge() {
var i = 1;
for (i = 1; i <= 100; i++) {
document.write("<option value=" + i + ">" + i + "</option>");
}
}
I believe the problem is that you try to take some values from fields that not exists at least from the code that you provided! Just copy the code above and it should work for sure!