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

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

Related

How to access HTML array object in javascript?

sorry for asking simple question. I am really a beginner in Javascript. I need to access my HTML array form object in my javascript, but I don't know how to do it.
The goal is to trigger the alert in javascript so the browser will display message according to the condition in javascript. Here is my code :
checkScore = function()
{
//I don't know how to access array in HTML Form, so I just pretend it like this :
var student = document.getElementByName('row[i][student]').value;
var math = document.getElementByName('row[i][math]').value;
var physics = document.getElementByName('row[i][physics]').value;
if (parseInt(math) >= 80 ) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80 ){
alert(student + " ,You are good at physics");
}
student_score.row[i][otherinfo].focus();
student_score.row[i][otherinfo].select();
}
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]"></td>
<td><input type="number" name="row[1][math]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row[2][student]"></td>
<td><input type="number" name="row[2][math]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
<p>If you click the "Submit" button, it will save the data.</p>
We are going to leverage few things here to streamline this.
The first is Event Listeners, this removes all javascript from your HTML. It also keeps it more dynamic and easier to refactor if the table ends up having rows added to it via javascript.
Next is parentNode, which we use to find the tr that enclosed the element that was clicked;
Then we use querySelectorAll with an attribute selector to get our target fields from the tr above.
/*This does the work*/
function checkScore(event) {
//Get the element that triggered the blur
var element = event.target;
//Get our ancestor row (the parent of the parent);
var row = element.parentNode.parentNode;
//Use an attribute selector to get our infor from the row
var student = row.querySelector("[name*='[student]']").value;
var math = row.querySelector("[name*='[math]']").value;
var physics = row.querySelector("[name*='[physics]']").value;
var otherField = row.querySelector("[name*='[otherinfo]']");
if (parseInt(math, 10) >= 80) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics, 10) >= 80) {
alert(student + " ,You are good at physics");
}
otherField.focus();
otherField.select();
}
/*Wire Up the event listener*/
var targetElements = document.querySelectorAll("input[name*='math'], input[name*='physics']");
for (var i = 0; i < targetElements.length; i++) {
targetElements[i].addEventListener("blur", checkScore);
}
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<tr>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]" class='student'></td>
<td><input type="number" name="row[1][math]" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row1[2][student]"></td>
<td><input type="number" name="row[2][math]" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
Well, it follows your line of code exactly as it is (because you said you do not want to change the code too much).
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]"></td>
<td><input type="number" name="row[1][math]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row1[2][student]"></td>
<td><input type="number" name="row[2][math]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
JavaScript [Edited again using part of the #Jon P code, the query selector is realy more dynamic, and the value of the "other" field you requested is commented out]
//pass element to function, in html, only add [this] in parenteses
checkScore = function (element) {
//Get our ancestor row (the parent of the parent);
var row = element.parentNode.parentNode;
//Use an attribute selector to get our infor from the row
var student = row.querySelector("[name*='[student]']").value;
var math = row.querySelector("[name*='[math]']").value;
var physics = row.querySelector("[name*='[physics]']").value;
var other = row.querySelector("[name*='[otherinfo]']");
if (parseInt(math) >= 80) {
//other.value = student + " ,You are good at mathematic";
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80) {
//other.value = student + " ,You are good at physics";
alert(student + " ,You are good at physics");
}
otherField.focus();
otherField.select();
}
Tested :), and sorry about my english!
Try that, haven't tested it
var form = document.getElementsByName("student_score")[0];
var students = form.getElementsByTagName("tr");
for(var i = 0; i < students.length; i++){
var student = students[i].childnodes[0].value;
var math = students[i].childnodes[1].value;
var physics = students[i].childnodes[2].value;
if (parseInt(math) >= 80 ) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80 ){
alert(student + " ,You are good at physics");
}
}

Cannot set property 'innerHTML' of null with array

Could somebody tell what is wrong here? I have a form with validation of email address and what is supposed to do is when is correct to make a new array and to print below form and when it's not just one simple alert. This is HTML:
<form>
<table>
<tr>
<td>Your email address</td>
<td>
<input type="text" id="txtEmail">
</td>
</tr>
<tr>
<td>
<input type="button" value="Register me" onclick="check();">
</td>
</tr>
</table>
</form>
This is JS:
function check() {
var email = document.getElementById("txtEmail").value;
var reEmail = /^(\w)+(\d)*(\.\_)*#[a-z]{2,10}\.[a-z]{2,5}$/;
var correct = new Array();
if(email.match(reEmail)){
correct.push(email);
document.getElementById("prikaz").innerHTML = correct;
}
else {
alert("Not correct");
}
}
Your HTML should be like this:
<form>
<table>
<tr>
<td>Your email address</td>
<td>
<input type="text" id="txtEmail">
</td>
</tr>
<tr>
<td>
<input type="button" value="Register me" onclick="check();">
</td>
</tr>
<tr>
</table>
</form>
<div id="prikaz">
</div>
And your JS should be like this:
var correct =new Array();
function check() {
var email = document.getElementById("txtEmail").value;
var reEmail = /^(\w)+(\d)*(\.\_)*#[a-z]{2,10}\.[a-z]{2,5}$/;
if(email.match(reEmail)){
correct.push(email);
}
else {
alert("Not correct");
}
var correctEmails = "<table>";
for(var i=0; i< correct.length; i++){
correctEmails+=("<tr><td>"+correct[i]+"</td></tr>");
}
correctEmails+="</table>"
document.getElementById("prikaz").innerHTML = correctEmails;
}
You have no element with the id "prikaz" so getElementById is returning null.
And even if it did return something, I don't see the point of setting it's innerHTML to an array since that field is for text that will be parsed as HTML.

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)'/>

how to validate form and sending email

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?

Categories

Resources