how to validate form and sending email - javascript

i have one form that validate form fields with javascript and sending email with VBscript. how ever validation works fine but email not sent to email account.
VBScript to sending email:
<%
posted = request.form ("submit")
if posted = "Submit" then
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'' Customize the following 5 lines with your own information. ''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
vtoaddress = "___________" ' Change this to the email address you will be receiving your notices.
vmailhost = "smtp.gmail.com" ' Change this to your actual Domain name.
vfromaddress = "___________" ' Change this to the email address you will use to send and authenticate with.
vfrompwd = "___________" ' Change this to the above email addresses password.
'''''''''''''''''''''''''''''''''''''''''''
'' DO NOT CHANGE ANYTHING PAST THIS LINE ''
'''''''''''''''''''''''''''''''''''''''''''
vsubject = request.form ("subject")
vfromname = request.form ("fname")
vbody = request.form ("message")
vrplyto = request.form ("email")
vrcity = request.form ("city")
vrmono = request.form ("phone")
vmsgbody = "<b>Name:</b> "& vfromname & "<br><b>Email:</b> "& vrplyto &"<br><b>Mobile No:</b> "& vrmono &"<br><b>City:</b> "& vrcity &"<br><b>Subject:</b> "& vsubject&"<br><b>Message:</b> "& vbody
Set objEmail = Server.CreateObject("CDO.Message")
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = vmailhost
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = 1
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername") = vfromaddress
objEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = vfrompwd
objEmail.Configuration.Fields.Update
objEmail.Subject = vsubject
objEmail.From = vfromaddress
objEmail.To=vfromaddress
objEmail.HTMLBody = vmsgbody
objEmail.Send
vErr = Err.Description
if vErr <> "" then
response.write vErr & "<br><br>There was an error on this page."
'MsgBox("There was an error on this page.")
else
response.write "Thank you, your message has been sent."
'MsgBox("Thank you, your message has been sent.")
End If
Set objEmail = Nothing
response.write "Thank you, your message has been sent."
'MsgBox("Thank you, your message has been sent.")
end if
%>
Javascript to validate form:
<script language="JavaScript">
<!--
function validate()
{
var count_bug=0;
if(document.form1.fname.value=="")
{
document.getElementById("alertMsgfname").innerHTML=" Enter Your First Name. ";
document.getElementById("alertMsgfname").style.visibility="visible";
if(eval(count_bug)==0)
document.form1.fname.focus();
count_bug+=1;
}
if(document.form1.email.value=="")
{
document.getElementById("alertMsgemail").innerHTML=" Enter Your E-mail. ";
document.getElementById("alertMsgemail").style.visibility="visible";
if(eval(count_bug)==0)
document.form1.email.focus();
count_bug+=1;
}
else if(!isEmail(document.form1.email.value))
{
document.getElementById("alertMsgemail").innerHTML=" Enter Valid E-mail! ";
document.getElementById("alertMsgemail").style.visibility="visible";
if(eval(count_bug)==0)
document.form1.email.focus();
count_bug+=1;
}
if(document.form1.phone.value=="")
{
document.getElementById("alertMsgphone").innerHTML=" Your Phone No. ";
document.getElementById("alertMsgphone").style.visibility="visible";
if(eval(count_bug)==0)
document.form1.phone.focus();
count_bug+=1;
}
else if(!ValidateNo(document.form1.phone.value," 1234567890,-/+"))
{
document.getElementById("alertMsgphone").innerHTML=" Invalid Phone No. ";
document.getElementById("alertMsgphone").style.visibility="visible";
if(eval(count_bug)==0)
document.form1.phone.focus();
count_bug+=1;
}
else if(document.form1.phone.value.length < 5)
{
document.getElementById("alertMsgphone").innerHTML=" Invalid Phone No. ";
document.getElementById("alertMsgphone").style.visibility="visible";
if(eval(count_bug)==0)
document.form1.phone.focus();
count_bug+=1;
}
if(document.form1.city.value=="")
{
document.getElementById("alertMsgCity").innerHTML=" Enter Your City Name. ";
document.getElementById("alertMsgCity").style.visibility="visible";
if(eval(count_bug)==0)
document.form1.city.focus();
count_bug+=1;
}
if(document.form1.subject.value=="")
{
document.getElementById("alertMsgSubject").innerHTML=" Enter Your Subject. ";
document.getElementById("alertMsgSubject").style.visibility="visible";
if(eval(count_bug)==0)
document.form1.subject.focus();
count_bug+=1;
}
if(document.form1.message.value=="")
{
document.getElementById("alertMsgMessage").innerHTML=" Enter Your Message. ";
document.getElementById("alertMsgMessage").style.visibility="visible";
if(eval(count_bug)==0)
document.form1.message.focus();
count_bug+=1;
}
if(count_bug>0)
return false;
else
return true;
}
function isEmail (emailIn){
var isEmailOk = false;
var filter = /^[a-zA-Z0-9][a-zA-Z0-9._-]*\#[a-zA-Z0-9-]+(\.[a-zA-Z][a-zA-Z-]+)+$/
// var filter = /^(([^<>()[\]\\.,;:\s#\”]+(\.[^<>()[\]\\.,;:\s#\”]+)*)|(\”.+\”))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
if(emailIn.search(filter) != -1)
isEmailOk = true;
if(emailIn.indexOf("..") != -1)
isEmailOk = false;
if(emailIn.indexOf(".#") != -1)
isEmailOk = false;
return isEmailOk;
}
function ValidateNo( NumStr, String )
{
for( var Idx = 0; Idx < NumStr.length; Idx ++ )
{
var Char = NumStr.charAt( Idx );
var Match = false;
for( var Idx1 = 0; Idx1 < String.length; Idx1 ++)
{
if( Char == String.charAt( Idx1 ) )
Match = true;
}
if ( !Match )
return false;
}
return true;
}
</script>
html form code:
<form name="form1" method="post" onsubmit="return validate();">
<table border="0" width="100%" cellspacing="0" cellpadding="0" class="table-format">
<tr valign="middle">
<td align="left" class="text-fm" width="23%" style="padding-top:8px;">
<b>Name<font color="#C70017">*</font></b></td>
<td align="left" class="text-fm" width="5%">
<b>:</b></td>
<td class="text-fm" align="left">
<input type="text" name="fname" id="fname" size="43" maxlength="40" class="inp">
<span id="alertMsgfname" class="valfrm" style='line-height:8px;'></span></td>
</tr>
<tr valign="middle">
<td align="left" class="text-fm" style="padding-top:8px;">
<b>Email Id<font color="#C70017">*</font></b></td>
<td align="left" class="text-fm">
<b>:</b></td>
<td class="text-fm" align="left">
<input type="text" name="email" id="email" size="43" maxlength="76" class="inp">
<span id="alertMsgemail" class="valfrm" style='line-height:8px;'></span></td>
</tr>
<tr valign="middle">
<td align="left" class="text-fm" style="padding-top:8px;">
<b>Mobile No.<font color="#C70017">*</font></b></td>
<td align="left" class="text-fm">
<b>:</b></td>
<td class="text-fm" align="left">
<input type="text" name="phone" id="phone" size="43" maxlength="16" class="inp">
<span id="alertMsgphone" class="valfrm" style='line-height:8px;'></span></td>
</tr>
<tr valign="middle">
<td align="left" class="text-fm" style="padding-top:8px;">
<b>City<font color="#C70017">*</font></b></td>
<td align="left" class="text-fm">
<b>:</b></td>
<td class="text-fm" align="left">
<input type="text" name="city" id="city" size="43" maxlength="76" class="inp">
<span id="alertMsgCity" class="valfrm" style='line-height:8px;'></span></td>
</tr>
<tr valign="middle">
<td align="left" class="text-fm" style="padding-top:8px;">
<b>Subject<font color="#C70017">*</font></b></td>
<td align="left" class="text-fm">
<b>:</b></td>
<td class="text-fm" align="left">
<input type="text" name="subject" id="subject" size="43" maxlength="76" class="inp">
<span id="alertMsgSubject" class="valfrm" style='line-height:8px;'></span></td>
</tr>
<tr valign="middle">
<td align="left" class="text-fm" style="padding-top:8px;">
<b>Message<font color="#C70017">*</font></b></td>
<td align="left" class="text-fm">
<b>:</b></td>
<td class="text-fm" align="left">
<textarea name="message" id="message" size="43" maxlength="16" class="inp" rows="6" cols="30"></textarea>
<span id="alertMsgMessage" class="valfrm" style='line-height:8px;'></span></td>
</tr>
<tr>
<td align="left" colspan="3">
<div align="center"><br>
<input type="submit" value="" name="Submit" class="imgClass"/>
<br>
</td>
</tr>
</table>
</form>

Absence of an error description doesn't imply the absence of an error. Change your error handling code to this:
If Err Then
response.write Err.Number & "<br><br>There was an error on this page."
Else
response.write "Thank you, your message has been sent."
End If
Are you able to connect from your webserver to the mailserver on port 465?
telnet smtp.gmail.com 465
Are you using correct credentials?
Do you have access to the mailserver logs? What do they say about connections from that page? If you don't have access to the actual mailserver, can you set up a dummy server and temporarily point the page to that server, so you can check if the code is working in principle?

Related

Having trouble displaying errors with Javascript Form Validation

I am using Regex to check my user input and then adding to an empty array called message when an error is found. I am having trouble displaying these errors along the top of the form
I am using Regex to check my user input and then adding to an empty array called message when an error is found. I am having trouble displaying these errors along the top of the form
<script>
function emailCheck(email) {
var re = /^[a-zA-Z\d]+\.[a-zA-Z\d]+#mohawkcollege.(?:com|ca|org)$/;
return re.test(email);
}
function phoneCheck(phone) {
var re = /^\b\d{3}[-.]?\d{3}[-.]?\d{4}\b$/;
return re.test(phone);
}
function postalCheck(postal){
var re = /^([a-zA-Z]\d[a-zA-Z])[\s\-]?(\d[a-zA-Z]\d)+$/;
return re.test(postal);
}
function streetCheck(street) {
var re = /^[1-9]{2,3} +[a-zA-Z]+ +(Street|street|road|Road)+$/;
return re.test(street);
}
function nameCheck(fname) {
var re = /^(mr\.|mrs\.|Mr\.|Mrs\.)\s+[a-zA-Z]+\s+[a-zA-Z]+$/;
return re.test(fname);
}
function errorCheck() {
var message = "";
var email = document.forms["myForm"]["email"].value;
var phone = document.forms["myForm"]["phone"].value;
var postal = document.forms["myForm"]["postal"].value;
var fname = document.forms["myForm"]["fname"].value;
var street = document.forms["myForm"]["street"].value;
if(phoneCheck(phone)) {
alert (phone + " is valid");
}
else{
message += "Phone invalid";
}
if(postalCheck(postal)) {
alert (postal + " is valid");
}
else {
message += "Postal invalid";
}
if (nameCheck(fname)) {
alert (fname + " is valid");
}
else {
message += "name invalid";
}
if (streetCheck(street)) {
alert (street + " is valid");
}
else {
message += "Street invalid";
}
if (emailCheck(email)) {
alert (email + " is valid");
}
else {
message += "email invalid";
}
return false;
$("#errorMessage").html(message);
}
</script>
here is the HTML
<html>
<body>
<p id="errorMessage"></p>
<link rel='stylesheet' type='text/css' href='Lab4.css'>
<table>
<tr>
<td class="top">
<a href=<?PHP echo $_SERVER["PHP_SELF"] ?>> Refresh ThisPage </a>
</td>
<td class="top">
Show Logfile.txt
</td>
<td class="top">
Show Logfile.txt Formatted
</td>
<td class="top">
Clear logfile.txt
</td>
</tr>
</table>
<form name="myForm" onsubmit="errorCheck()">
<table class="body">
<tr>
<td class="column1">
Full Name:
</td>
<td class="column2">
<input id="fname" type="text" >
</td>
<td class="column3">
Salution of Mr. and Mrs. followed by two text strings separated by any number of spaces
</td>
</tr>
<tr>
<td class="column1">
Street:
</td>
<td class="column2">
<input id="street" type="text" >
</td>
<td class="column3">
2 or 3 digit number followed by a text string ending with Street or Road separated by any number of space
</td>
</tr>
<tr>
<td class="column1">
PostalCode:
</td>
<td class="column2">
<input id = "postal" type="text" >
</td>
<td class="column3">
Char Char Digit optional Hyphen or space Char Digit Digit (abclxyz and number 0 not allowed. Case insensitive
</td>
</tr>
<tr>
<td class="column1">
Phone:
</td>
<td class="column2">
<input id = "phone" type="text" >
</td>
<td class="column3">
10 digits, first 3 digits have optional parentheses, either side of digits 456 are optional space, dot or hyphen
</td>
</tr>
<tr>
<td class="column1">
Email:
</td>
<td class="column2">
<input id="email" type="text">
</td>
<td class="column3">
firstname.lastname#mohawkcollege.domain (firstname and lastname must be 4-10 characters in length, domain may be either .com, .ca or .org)
</td>
</tr>
</table>
<br>
<input class="submit" type="submit" id="check" value="Submit me now!!!"/>
</form>
</body>
</html>
You are returning from errorCheck() before you set the content of #errorMessage.
I moved the html() call before return and made message an array (as you said) so you can display the messages in a list format.
function emailCheck(email) {
var re = /^[a-zA-Z\d]+\.[a-zA-Z\d]+#mohawkcollege.(?:com|ca|org)$/;
return re.test(email);
}
function phoneCheck(phone) {
var re = /^\b\d{3}[-.]?\d{3}[-.]?\d{4}\b$/;
return re.test(phone);
}
function postalCheck(postal) {
var re = /^([a-zA-Z]\d[a-zA-Z])[\s\-]?(\d[a-zA-Z]\d)+$/;
return re.test(postal);
}
function streetCheck(street) {
var re = /^[1-9]{2,3} +[a-zA-Z]+ +(Street|street|road|Road)+$/;
return re.test(street);
}
function nameCheck(fname) {
var re = /^(mr\.|mrs\.|Mr\.|Mrs\.)\s+[a-zA-Z]+\s+[a-zA-Z]+$/;
return re.test(fname);
}
function errorCheck() {
var message = [];
var email = document.forms["myForm"]["email"].value;
var phone = document.forms["myForm"]["phone"].value;
var postal = document.forms["myForm"]["postal"].value;
var fname = document.forms["myForm"]["fname"].value;
var street = document.forms["myForm"]["street"].value;
if (phoneCheck(phone)) {
alert(phone + " is valid");
} else {
message.push("Phone invalid");
}
if (postalCheck(postal)) {
alert(postal + " is valid");
} else {
message.push("Postal invalid");
}
if (nameCheck(fname)) {
alert(fname + " is valid");
} else {
message.push("name invalid");
}
if (streetCheck(street)) {
alert(street + " is valid");
} else {
message.push("Street invalid");
}
if (emailCheck(email)) {
alert(email + " is valid");
} else {
message.push("email invalid");
}
$("#errorMessage").html(`<ul><li>${message.join('</li><li>')}</li></ul>`);
return false;
}
#errorMessage {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="errorMessage"></p>
<table>
<tr>
<td class="top">
</td>
<td class="top"> Show Logfile.txt </td>
<td class="top"> Show Logfile.txt Formatted </td>
<td class="top"> Clear logfile.txt </td>
</tr>
</table>
<form name="myForm">
<table class="body">
<tr>
<td class="column1">Full Name:</td>
<td class="column2">
<input id="fname" type="text">
</td>
<td class="column3">Salution of Mr. and Mrs. followed by two text strings separated by any number of spaces</td>
</tr>
<tr>
<td class="column1">Street:</td>
<td class="column2">
<input id="street" type="text">
</td>
<td class="column3">2 or 3 digit number followed by a text string ending with Street or Road separated by any number of space</td>
</tr>
<tr>
<td class="column1">PostalCode:</td>
<td class="column2">
<input id="postal" type="text">
</td>
<td class="column3">Char Char Digit optional Hyphen or space Char Digit Digit (abclxyz and number 0 not allowed. Case insensitive</td>
</tr>
<tr>
<td class="column1">Phone:</td>
<td class="column2">
<input id="phone" type="text">
</td>
<td class="column3">10 digits, first 3 digits have optional parentheses, either side of digits 456 are optional space, dot or hyphen</td>
</tr>
<tr>
<td class="column1">Email:</td>
<td class="column2">
<input id="email" type="text">
</td>
<td class="column3">firstname.lastname#mohawkcollege.domain (firstname and lastname must be 4-10 characters in length, domain may be either .com, .ca or .org)</td>
</tr>
</table>
<br>
<input class="submit" type="button" onclick="errorCheck()" id="check" value="Submit me now!!!" />
</form>

Form validation without error on IE

I have a html code saved as a php, the form validation works in google chrome but not in IE. In IE after I hit the submit button, the page automatically goes to process form regardless of errors.
This is my code:
<!DOCTYPE html>
<html>
<head>
<title>Week 8 Lab - JavaScript DOM and Arrays</title>
<meta charset="utf-8">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<script>
function validateForm() {
var errors = 0;
var fName = document.forms["orderForm"].firstName.value;//first name validation
if (fName == null || fName == "")
{
document.getElementById('firstNameError').innerHTML = "Please enter a first name.";
errors++;
} else {
document.getElementById('firstNameError').innerHTML = "";
}
//var lName = document.forms["orderForm"].lastName.value;//last name validation
if (lName == null || lName == "")
{
document.getElementById('lastNameError').innerHTML = "Please enter a last name.";
errors++;
} else {
document.getElementById('lastNameError').innerHTML = "";
}
//var address = document.forms["orderForm"].address.value;//address validation
if (address == null || address == "")
{
document.getElementById('addressError').innerHTML = "Please enter an address.";
errors++;
} else {
document.getElementById('addressError').innerHTML = "";
}
//var city = document.forms["orderForm"].city.value;//city validation
if (city == null || city == "")
{
document.getElementById('cityError').innerHTML = "Please enter a city.";
errors++;
} else {
document.getElementById('cityError').innerHTML = "";
}
//var pCodeCheck = /^[0-9a-zA-Z]+$/;//postal code validation
if (pCodeCheck)
{
document.getElementById('postalCoderror').innerHTML = "";
}
else
{
document.getElementById('postalCoderror').innerHTML = "Please enter a valid postal code.";
errors++;
}
// makes sure you cannot order a negative number of items
var itemQTY = document.forms["orderForm"].widget1qty.value;
if (itemQTY < 0)
{
document.getElementById('qtyError').innerHTML = "You cannot enter a negative number.";
errors++;
} else {
document.getElementById('qtyError').innerHTML = "";
}
var itemQTY2 = document.forms["orderForm"].widget2qty.value;
if (itemQTY2 < 0)
{
document.getElementById('qtyError2').innerHTML = "You cannot enter a negative number.";
errors++;
} else {
document.getElementById('qtyError2').innerHTML = "";
}
var itemQTY3 = document.forms["orderForm"].widget3qty.value;
if (itemQTY3 < 0)
{
document.getElementById('qtyError3').innerHTML = "You cannot enter a negative number.";
errors++;
} else {
document.getElementById('qtyError3').innerHTML = "";
}
//makes sure there is at least one item ordered
var wid1Qty = document.getElementById('widget1qty').value;
var wid2Qty = document.getElementById('widget2qty').value;
var wid3Qty = document.getElementById('widget3qty').value;
if (wid1Qty + wid2Qty + wid3Qty == 0)
{
document.getElementById('itemQTY').innerHTML = "You must order atleast one item.";
errors++;
} else {
document.getElementById('itemQTY').innerHTML = "";
}
var total1;
var total2;
var total3;
var total4;
total1 = document.forms['orderForm']['widget1qty'].value * 5;
total2 = document.forms['orderForm']['widget2qty'].value * 15;
total3 = document.forms['orderForm']['widget3qty'].value * 25;
total4 = (total1 + total2 + total3);
alert('Your total is: $' + total4 + '.00');
return errors;
}
function startValidate() {
var errors = validateForm();
if (errors == 0) {
document.forms['orderForm'].submit();
} else {
return false;
}
}
</script>
<div id="wrapper">
<h2 class="center">Order Form</h2> <!-- action="processForm.html" "javascript:void(0)" -->
<form name="orderForm" method="post" action="processForm.html" onsubmit="return startValidate()">
<fieldset>
<legend>Personal Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td><span class="required">*</span>First Name:</td>
<td><input type="text" name="firstName" id="firstName" size="30"></td>
<td id="firstNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Last Name:</td>
<td><input type="text" name="lastName" id="lastName" size="30"></td>
<td id="lastNameError"></td>
</tr>
<tr>
<td><span class="required">*</span>Address:</td>
<td><input type="text" name="address" id="address" size="30"></td>
<td id="addressError"></td>
</tr>
<tr>
<td><span class="required">*</span>City:</td>
<td><input type="text" name="city" id="city" size="30"></td>
<td id="cityError"></td>
</tr>
<tr>
<td><span class="required">*</span>Province:</td>
<td><select name="province" id="province" size="1">
<option disabled>Select a province</option>
<option value="BC">British Columbia</option>
<option value="AB">Alberta</option>
<option value="SK">Saskatchewan</option>
<option value="MB">Manitoba</option>
<option value="ON">Ontario</option>
<option value="QC">Quebec</option>
<option value="NB">New Brunswick</option>
<option value="NS">Nova Scotia</option>
<option value="PE">Prince Edward Island</option>
<option value="NF">Newfoundland</option>
<option value="YK">Yukon</option>
<option value="NWT">Northwest Territories</option>
<option value="NU">Nunavut</option>
</select>
</td>
<td></td>
</tr>
<tr>
<td><span class="required">*</span>Postal Code:</td>
<td><input type="text" name="postalCode" id="postalCode" maxlength="6"></td>
<td id="postalCoderror"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Order Information</legend>
<table>
<tr>
<th colspan="3"></th>
</tr>
<tr>
<td rowspan="3">Select your products:<br>
<td>Widget #1
<input type="text" name="widget1qty" id="widget1qty" size="1" value="0">Qty # <strong>$5.00/ea</strong></td>
<td id="qtyError"></td>
</tr>
<tr>
<td>Widget #2
<input type="text" name="widget2qty" id="widget2qty" size="1" value="0">Qty # <strong>$15.00/ea</strong></td>
<td id="qtyError2"></td>
</tr>
<tr>
<td>Widget #3
<input type="text" name="widget3qty" id="widget3qty" size="1" value="0">Qty # <strong>$25.00/ea</strong></td>
<td id="qtyError3"></td>
</tr>
<tr>
<td rowspan="3"></td>
<td></td>
<td id="itemQTY"></td>
</tr>
<tr>
<td rowspan="3">Shipping Type:</td>
<td>Standard ($5.00)<input type="radio" name="shippingType" id="shippingTypeStandard" value="Standard" checked></td>
</tr>
<tr>
<td>Express ($10.00)<input type="radio" name="shippingType" id="shippingTypeExpress" value="Express"></td>
</tr>
<tr>
<td>Overnight ($20.00)<input type="radio" name="shippingType" id="shippingTypeOvernight" value="Overnight"></td>
</tr>
</table>
</fieldset>
<fieldset>
<legend>Submit Order</legend>
<table>
<tr>
<th colspan="2"></th>
</tr>
<tr>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit Order">
<td><input type="reset" name="btnReset" id="btnReset" value="Reset Form"></td>
</tr>
</table>
</fieldset>
</form>
</div>
</body>
When you look at the console in IE’s developer tools (F12), you will see that there is an error message about undeclared variable lName. This causes the error checking to be aborted.
You have several lines like
//var lName = document.forms["orderForm"].lastName.value;//last name validation
Since // starts a comment in JavaScript, the line has no effect. The variable lName is not declared or defined elsewhere either.
So you need to remove those // comment starters. Note that the code does not work in Chrome either; you may have tested a different version in Chrome, or misinterpreted some behavior.
In the console, you can also see a message for line 237 about “unexpected identifier”. It is actually a serious HTML markup error; IE reports some of such errors, in a strange way. The error is that a tr element has an input element as child, which is forbidden in HTML syntax. This is why the Submit Order and Reset Form appear on top of each other and not on the same row as intended. (For usability, the Reset Form button should be removed, but I digress.)

window.location.href still not working after cancelling form submission

I have an login form
<div id='login_form'>
<table>
<tr>
<td>Username:</td>
<td><input size=25 type='text' id='username'></td>
</tr>
<tr>
<td>Password:</td>
<td><input size=25 type='password' id='password'></td>
</tr>
<tr>
<td colspan='2' align='right'>
<input type='button' id='login' value='Login' onkeydown='normalobjKeyFunc(this)' onfocus='itemFocus(this)' onblur='itemBlur(this)'/>
</td>
</tr>
</table>
</div>
then I have javaScript
var input_username = document.getElementById("username").value;
var input_password = document.getElementById("password").value;
if(input_username === "123" && input_password === "456"){
alert("Correct username & password");
window.location.href="../../result.html";
return false;
}
But when I received the alert "Correct username & password", the page was not redirected to result.html. And I checked, "../../result.html" exists.
I found some people said the submission should be cancelled, so I deleted form and changed the " type = "submit" " to " type = "button" "for Login button, but it was not working.
And there is also another method, add "return false" after " window.location.href="../../result.html" ", but it was not working as well.
Any one has any idea????
Thanks in advance!
Username/password checking should be done on the backend (Java, PHP, Node, .NET)
Your form should be in a form tag though. The checking should be done in the onsubmit callback:
<script>
function authenticate(){
var input_username = document.getElementById("username").value;
var input_password = document.getElementById("password").value;
if(input_username==="123"&&input_password==="456"){
alert("Correct username & password");
window.location.href = "../../result.html";
}
else {
// Error
}
return false;
}
</script>
<form onsubmit="authenticate()">
<table>
<tr>
<td>Username:</td>
<td><input size="25" type="text" id="username"></td>
</tr>
<tr>
<td>Password:</td>
<td><input size="25" type="password" id="password"></td>
</tr>
<tr>
<td colspan="2" style="text-align: right">
<button onkeydown="normalobjKeyFunc(this)" onfocus="itemFocus(this)" onblur="itemBlur(this)">Login</button>
</td>
</tr>
</table>
</form>
Put an onclick in your button to call your javascript function..
<input type='button' id='login' onclick="authenticate()" value='Login' onkeydown='normalobjKeyFunc(this)' onfocus='itemFocus(this)' onblur='itemBlur(this)'/>

JavaScript checking & adding text to a table dynamically on submit button click

Basically my HTML looks like this:
<form method="post" name="htmlform" onsubmit = "checkFields()">
<table style="width: 479px;" border="30" cellspacing="3" cellpadding="10">
<tbody>
<tr>
<td valign="top"><span id="firstNameSpan" >First Name *</span></td>
<td valign="top"><input type="text" name="first_name" id="first_name"
size="30" maxlength="50" /></td>
</tr>
<tr>
<td valign="top"><span id = "lastNameSpan" >Last Name *</span></td>
<td valign="top"><input type="text" name="last_name" size="30" maxlength="50"/>
/td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="radio" name="sex"
value="male" /> Male <input type="radio" name="sex"
value="female" /> Female</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="submit" value="submit"
/></td>
</tr>
</tbody>
</table>
</form>
When the form is submitted, the onsubmit() event checks if first_name textfield is blank, if it is then the label or span to its left is appended to output "first name*" + " you must enter a first name" and similarly for last name and sex.
The problem is that the text in the table does not update with appendchild. When I enclosed the statement in an alert for debugging the message is appended then disappears.
The JavaScript code is below for the onsubmit = "checkFields()".
function checkFields() {
var firstName = document.getElementById("first_name").value;
var lastName = document.getElementById("last_name").value;
if (firstName == "") {
//<span style='color:red'> Please enter a first name </span>
var nameHint = " Please enter a first name";
var node = document.getElementById("firstNameSpan");
//alert(node.appendChild(document.createTextNode(nameHint)) );
//not working
node.appendChild(document.createTextNode(nameHint));
} if (lastName == "") {
//additional code
}
}
Thanks in advance, your help is much appreciated. Also are there any JavaScript debuggers?
Regards
David D
I believe your sample code is not working due to incorrect html. document.getElementById("last_name") will return undefined.
http://jsfiddle.net/5E6my/1/
Thanks all, Im getting the ropes of JFiddle the split screen is very useful although the error messages are not useful for debugging. Here is the completed code (1) HTML (2) JavaScript.
<form method="post" name="htmlform" onsubmit="return checkFields();">
<table style="width: 479px;" border="30" cellspacing="3" cellpadding="10">
<tbody>
<tr>
<td valign="top"><span id="firstNameSpan" >First Name *</span></td>
<td valign="top"><input type="text" name="first_name" id="first_name"
size="30" maxlength="50" /></td>
</tr>
<tr>
<td valign="top"><span id = "lastNameSpan" >Last Name *</span></td>
<td valign="top"><input type="text" name="last_name" id="last_name" size="30"
maxlength="50" /></td>
</tr>
<tr>
<td style="text-align: center;" colspan="2" id = "sexMessage">
Please select Male or Female*</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="radio"
name="sex" value="male" /> Male <input type="radio" name="sex"
value="female" /> Female</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="submit" value="submit"
/></td>
</tr>
</tbody>
</table>
</form>
The JavaScript code to react to the onsubmit button's unfilled fields in the form are: (any ways to make this code simpler??)
window.checkFields = function()
{
var firstName = document.getElementById("first_name");
var lastName = document.getElementById("last_name");
if(firstName.value == "")
{
//<span style='color:red'> Please enter a first name </span>
var nameHint = " *Please enter a first name ";
var fnNode = document.getElementById("firstNameSpan");
while(fnNode.firstChild)
{
fnNode.removeChild(fnNode.firstChild)
}
fnNode.appendChild(document.createTextNode(nameHint));
fnNode.style.color="red";
} else{
var nameHint = " First Name *";
var fnNode = document.getElementById("firstNameSpan");
while(fnNode.firstChild)
{
fnNode.removeChild(fnNode.firstChild)
}
fnNode.appendChild(document.createTextNode(nameHint));
fnNode.style.color="black";
}
if (lastName.value == "")
{
//additional code
var nameHint = " *Please enter a last name";
var lnNode = document.getElementById("lastNameSpan");
while(lnNode.firstChild)
{
lnNode.removeChild(lnNode.firstChild)
}
lnNode.appendChild(document.createTextNode(nameHint));
lnNode.style.color="red";
} else{
var nameHint = " Last Name *";
var lnNode = document.getElementById("lastNameSpan");
while(lnNode.firstChild)
{
lnNode.removeChild(lnNode.firstChild)
}
lnNode.appendChild(document.createTextNode(nameHint));
lnNode.style.color="black";
}
var radios = document.getElementsByName("sex");
var radioValue = ""
for(var i=0; i<radios.length; i++)
{
if(radios[i].checked)
{
radioValue = radios[i].value;
}
}
if(radioValue === "")
{
var sexNode = document.getElementById("sexMessage");
var nameHint = "*You did not choose a sex";
while(sexNode.firstChild)
{
sexNode.removeChild(sexNode.firstChild);
}
sexNode.appendChild(document.createTextNode(nameHint));
sexNode.style.color="red";
} else {
var sexNode = document.getElementById("sexMessage");
var nameHint = "Please select Male or Female*";
while(sexNode.firstChild)
{
sexNode.removeChild(sexNode.firstChild);
}
sexNode.appendChild(document.createTextNode(nameHint));
sexNode.style.color="black";
}
return false;
}
The trick is to use as Yury suggested was the onsubmit="return checkfields()" and then in the code block to use window.checkFields = function() { etc.
One question that I have... is JQuery a lot simpler to use, im learning JavaScript before JQuery... should I skip to JQUery instead. Also does JQuery support the AJAX framework?
Much appreciated
David

Form "submit" working in IE but not Firefox and Chrome

I have a sign up form on my site which works OK in IE but does not work in Firefox or Chrome. I have tried looking through other forum posts here with similar problems but still can't get my head round this silly problem. (I am not a code writer).
Here is the code
<script type="text/JavaScript">
function validate_form(){
{validation_text}
else{
return true;
}
}
var str_vars = '';
function all_fields(){
str_vars = '';
el = document.form1;
for (var i = 0; i < el.elements.length; i++) {
if (el.elements[i].value != '')
str_vars += el.elements[i].name+'='+el.elements[i].value+'&';
}
str_vars = str_vars.substr(0,str_vars.length-15);;
}
</script>
<div id="div_form" name="div_form">
<form id="form1" name="formx" method="{send_method}" action="{form_switch}">
<p> </p>
<table border="0" width="100%" style="border-collapse: collapse" bordercolor="#111111" cellpadding="0" cellspacing="0">
{error}
{signup_list}
<tr>
<td align="right">{description_country} </td>
<td>{shiping_country_list}{required_country}</td>
</tr>
<tr><td align="right"> {promo}</td></tr>
{code_signup}
<tr>
<td colspan="2"><div align="center">
<input name="terms" id="terms" value="1" type="checkbox">
<label for="terms">I accept the terms & conditions</label>
</div></td>
</tr>
<tr>
<td colspan="2"><div align="center">
{captcha}</td>
</tr>
{arp_fields}
<tr>
<td><div align="right">*</div><br></td>
<td width="332">Denotes required</td>
</tr>
<tr>
<td>
<div align="right">
<input name="Submit" value="Submit" type="button" onclick="{request}{request_email}{form2items}">
</div></td>
<td> <br></td>
</tr>
</table>
</form>
</div>
</div>
Any help would be appreciated.
Maybe instead of
el = document.form1;
try
el = document.getElementById('form1');
I can't see all the JS so it is hard to guess, but one other thing to try is to change the name of the submit button from name="Submit" to something else like name="submitForm". If form.submit() is getting called somewhere in the script this can cause problems.
Your validate function should look something like this:
function validate_form(){
var form = document.getElementById('form1');
err = 'The following fields are not correct filled:\n';
if (form.first_name.value == ''){
err += 'No First Name.\n';
}
if (emailCheck(form.email.value) == false){
err += 'No Valid email.\n';
}
if (form.terms.checked != true){
err += 'You did not agree with the terms.\n';
}
if (err != 'The following fields are not correct filled:\n'){
alert (err);
return false;
}
else{
return true;
}
}
Lastly, change your submit button to this:
<input name="Submit" value="Submit" type="button" onclick="if (validate_form()) document.getElementById('form1').submit();">

Categories

Resources