Javascript onclick with if statement [duplicate] - javascript

This question already has answers here:
How does the single equal sign work in the if statement in javascript
(6 answers)
What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)
(5 answers)
Closed 3 years ago.
Hello guys I'm really new to javascript,
I want an alert message to appear if the user pressed on check,
to see if the input was right or wrong,
and I've been trying for so long but it's not working no matter what, it's just a simple code.
I'm really suffering with this for hours, trying to figure why no alert message appears when I press on the check button.
Would be really grateful for any help or any tip, many thanks!!
function myFunction() {
var x = document.getElementById("f").value;
var z = document.getElementById("s").value;
var c = document.getElementById("e").value;
var v = document.getElementById("p").value;
var b = document.getElementById("p1").value;
if (isNaN(x) || x = "") {
alert("First Name input is wrong");
} else {
alert("Input is ok");
}
if (isNaN(z) || z = "") {
alert("Second Name input is wrong");
} else {
alert("Input is ok");
}
if (isNaN(c) || c = "") {
alert("Email input is wrong");
} else {
alert("Input is ok");
}
if (v = "") {
alert("Input is wrong");
} else {
alert("Input is ok");
}
if (b = "" || b !== v) {
alert("Password does not match");
else {
alert("Input is ok");
}
}
}
<div class="event">
<h1> Event Planning</h1>
</div>
<div class="back">
<table border="1">
<form action="submit.php" method="post">
<tr>
<th colspan="2"> Sign UP</th>
</tr>
<tr>
<td> First Name </td>
<td> <input type="text" name="FirstName" id="f"></td>
</tr>
<tr>
<td> Second Name</td>
<td> <input type="text" name="SecondName" id="s"></td>
</tr>
<tr>
<td> Email Address</td>
<td> <input type="email" name="email" id="e"> </td>
</tr>
<tr>
<td> Password</td>
<td> <input type="password" name="psd" id="p"> </td>
</tr>
<tr>
<td> Repeat Password</td>
<td> <input type="password" name="psd2" id="p1"> </td>
</tr>
<tr>
<td colspan="2"> <input type="submit" name="submit" value="submit">
<button type="button" id="but" onclick="myFunction()">Check</button></td>
</tr>
</form>
</table>

You have a few syntax errors in your function.
Javascript requires == (or ===) for comparisons.
You also need to add a curly brace } before the else after "Password does not match", and remove one after the following "Input is ok".

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>

Radio button 'onclick' works in Chrome and Firefox but not IE

We are trying to develop a very simple HTML/JavaScript advising tool for students. It gives advice on which courses to take after the student checks radio buttons describing his or her high school GPA and standardized test score. The current version works correctly in both Chrome and Firefox, displaying its results after both radio buttons have been checked. In IE11, the page displays and the user can check buttons, but no response is given when the second button is checked. How should we make this independent of (current) browser?
A stripped-down version is posted below, containing enough code to demonstrate the basic behavior and problem.
function calc() {
//sets all the variables to blank
gpa109 = ""
gpa115 = ""
note = ""
//The value of the GPA radio button input is set in the GPA variable (first button=1, etc...)
GPA = document.data.GPA.value
//The value of the ACT radio button input is set in the ACT variable (first button=1, etc...)
ACT = document.data.ACT.value
//Use if-then statements to assign gpa output values to variables based on GPA and ACT inputs
//gpa output variables are gpa109, gpa115, gpa109120, etc...
//the note in the text box at the end is in variable "note"
if (GPA == 1) {
if (ACT == 1) {
gpa109 = "0.91"
}
}
if (GPA == 1) {
if (ACT == 1) {
gpa115 = "No Data"
}
}
if (GPA == 1) {
if (ACT == 2) {
gpa109 = "1.50"
}
}
if (GPA == 1) {
if (ACT == 2) {
gpa115 = "No Data"
}
}
if (GPA == 2) {
if (ACT == 1) {
gpa109 = "1.68"
}
}
if (GPA == 2) {
if (ACT == 1) {
gpa115 = "No Data"
}
}
if (GPA == 2) {
if (ACT == 2) {
gpa109 = "1.98"
}
}
if (GPA == 2) {
if (ACT == 2) {
gpa115 = "1.27"
}
}
if (GPA == 1) {
if (ACT == 1) {
note = "we are worried about you."
}
}
if (GPA == 1) {
if (ACT == 2) {
note = "slacked off a bit in high school, did you not?"
}
}
if (GPA == 2) {
if (ACT == 1) {
note = "you are a classic bad standardized test taker."
}
}
if (GPA == 2) {
if (ACT == 2) {
note = "you should probably apply to a better college."
}
}
//These statements put all the values determined by the if-then statements into the document
document.data.gpa109.value = gpa109
document.data.gpa115.value = gpa115
document.data.note.value = note
}
<form name="data">
<table COLS=4 cellpadding=2 border=1 align=center>
<tr>
<td COLSPAN="4">
<center><b><font size=+2>
<p>
Advising Tool
</p></font></b>
</center>
</td>
</tr>
<tr>
<td COLSPAN="2">
<center><font size=+1>
<p>
What was your High School GPA?
</p>
</font>
</center>
</td>
<td COLSPAN="2">
<center><font size=+1>
<p>
What was your ACT Math subscore?
<p>
</font>
</center>
</td>
</tr>
<tr>
<td COLSPAN="2">
<center>
<font size=+1>
<P>
<input type="radio" name="GPA" value="1" onclick="calc();"> Less than 3.5<br>
<input type="radio" name="GPA" value="2" onclick="calc();"> 3.5 or greater<br>
</P></font>
</center>
</td>
<td COLSPAN="2">
<center><font size=+1>
<P>
<input type="radio" name="ACT" value="1" onclick="calc();"> Less than 26<br>
<input type="radio" name="ACT" value="2" onclick="calc();"> 26 or greater<br>
</P> </font>
</center>
</td>
</tr>
<tr>
<td COLSPAN="4" align="center">
<font size=+1>
<br>
Over the past 5 years, students with similar high school GPAs and ACT Math<br>scores had the following average GPA in their introductory CHM courses.
<br>
<br>
</font>
</td>
</tr>
<tr>
<td align="right">
Classes Taken
</td>
<td>
Average GPA
</td>
</tr>
<tr>
<td align="right">
CHM 109 Only
</td>
<td>
<input name="gpa109" size="10" type="text">
</td>
<tr>
<td align="right">
CHM 115 Only
</td>
<td>
<input type="text" name="gpa115" size="10">
</td>
<tr>
<td COLSPAN="4" align="center">
<textarea rows="2" cols="100" name="note">
</textarea>
</td>
</tr>
</table>
</form>
Your problem is here, document.data.GPA.value, where the GPA is an array of objects, so you need to access the value like this
document.data.GPA[0].value;
As a side note, the code you posted is filled with obsolete elements, like center, font, so I recommend you do a clean up, and using table for layout is outdated, check out for example flexbox, which is excellent for this
Update
What I mean with read a value of an array of objects is to do something like this
var v = document.querySelectorAll('input[name=GPA]');
for(var i = 0; i < v.length; i++){
if(v[i].checked){
GPA = v[i].value;
}
}
There is also document.querySelector
GPA = document.querySelector('input[name=GPA]:checked').value;
Or the classic form.elements syntax
document.data.elements['GPA'].value;

Can't get JavaScript method to validate my HTML form

I'm trying to use a javascript method to validate my form but it doesn't seem to be working. No dialog box pops up warning me of any errors even if an empty form is submitted. What could be the error?
(Please Note: The JS File has a method defined for a time-stamp that I am currently not using in my form tag. I need some help with calling two functions as well.)
Here's the code:
function setDate() {
document.getElementById('date').value = new Date();
}
function validateForm() {
var a = document.getElementById('name').value;
var b = document.getElementById("contact1").value;
var blen = b.length;
var c = document.getElementById("address1").value;
var d = document.getElementById("stblimit").value;
var dlen = d.length;
var e = document.getElementById("creditlimit").value;
var f = document.getElementById("commission").value;
var g = document.getElementById("servicecharges").value;
//DATE var h = document.forms["addRetailer"]["date"].value;
if (a == null || a == "") {
alert("Name must be filled out");
return false;
} else if (b == null || b == "" || blen == 0 || blen > 10 || blen < 10) {
alert("Enter a valid number");
return false;
} else if (c == null || c == "") {
alert("Primary Address must be filled out");
return false;
} else if (d == null || d == "" || dlen == 0 || dlen < 0) {
alert("Set Box Top Limit must be filled with a valid number");
return false;
} else if (e == null || e == "") {
alert("Credit Limit must be filled out");
return false;
} else if (f == null || f == "") {
alert("Commission Percentage must be filled out");
return false;
} else if (g == null || g == "") {
alert("Service Charges must be filled out");
return false;
}
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="formvalidation.js" type="text/javascript"></script>
<title>Register Retailer</title>
</head>
<body>
<h1>Retailer Information</h1>
<form name="addRetailer" action="RetailerController" method="post" onsubmit="return validateForm()">
<table>
<tr>
<td>Name</td>
<td>
<input type="text" name="name" id="name"></input>
</td>
</tr>
<tr>
<td>Contact Number 1</td>
<td>
<input type="text" name="contact1" id="contact1"></input>
</td>
</tr>
<tr>
<td>Contact Number 2</td>
<td>
<input type="text" name="contact2" id="contact2"></input>
</td>
</tr>
<tr>
<td>Address Line 1</td>
<td>
<input type="text" name="address1" id="address1"></input>
</td>
</tr>
<tr>
<td>Address Line 2</td>
<td>
<input type="text" name="address2" id="address2"></input>
</td>
</tr>
<tr>
<td>City</td>
<td>
<input type="text" name="city" id="city"></input>
</td>
</tr>
<tr>
<td>State</td>
<td>
<input type="text" name="state" id="state"></input>
</td>
</tr>
<tr>
<td>Pin Code</td>
<td>
<input type="text" name="pin" id="pin"></input>
</td>
</tr>
<tr>
<td>Set Top Box Limit</td>
<td>
<input type="text" name="stblimit" id="stblimit" value="0"></input>
</td>
</tr>
<tr>
<td>Credit Limit</td>
<td>
<input type="text" name="creditlimit" id="creditlimit"></input>
</td>
</tr>
<tr>
<td>Commission Percentage</td>
<td>
<input type="text" name="commission" id="commission" value="0.0"></input>
</td>
</tr>
<tr>
<td>Service Charges</td>
<td>
<input type="text" name="servicecharges" id="servicecharges"></input>
</td>
</tr>
<tr>
<td>Date of Registration</td>
<td>
<input type="text" name="date" id="date"></input>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="hidden" value="registerCustomer" name="action"></input>
<input type="submit" value="Register"></input>
</td>
</tr>
</table>
</form>
<br>
<br>Click
Home To Return To The Main Screen
</body>
</html>
EDIT:
Here is a screenshot of my Eclipse IDE workspace. My js file and html file aren't in the same sub-folder, although they are under 'Web Content'. Could that be the issue?
Screenshot of Eclipse IDE Workspace
You may not have linked your JS file properly.
Looking at your screenshot I noticed you're using Tomcat and Java EE, which follows Unix style syntax for it's directory on the web server.
Your directory:
-Webcontent/
-WEB-INF/
+addRetailer
-JavaScript/
+validateForm.js
So, your HTML file is in WEB-INF which is under Webcontent and the form validator is under javascript, also under webcontent.
There's three solutions I have for this:
Move the JavaScript folder into WEB-INF and change the script reference to: "JavaScript/formvalidation.js"
Change the script reference to jump 'up' a directory layer using the double-dot'..' which should end up being: "../JavaScript/formvalidator.js"
Use HTML5's form validation instead, which doesn't need JavaScript. and is much neater. You can find details on the Mozilla Dev Network here.
Using Chrome, it seems to work for me:
The only thing that I changed is that I removed the link to the external JS file. It is possible the error is there and preventing your code from running. Check that file.

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