I have an HTML file, JavaScript file and a PHP file. The JavaScript is used to validate the user input and then to pass the form into the PHP page.
The validation function is working great, but the form will not submit from the JavaScript to the PHP file.
After spending two days on this, I still can not figure out what I have wrong and why the JavaScript will not submit the form data into the PHP file and how to get the PHP page to appear after submitting
HTML:
<div class = "formtext">
<p>
<form id = "formtext" name="survey" method="post" action="formtext.php">
<table id="surveytable" width="300" border="1">
<tr>
<td>
Name:
<input type = "text" id="userName"
name="name" onkeyup="document.getElementById('mirror').innerHTML=this.value" />
<br/ >
Your name: <span id="mirror"></span>
</td>
</tr>
<tr>
<td>
Number:
<input type = "text" id="userNumber"
name="number" onkeyup="document.getElementById('mirror1').innerHTML=this.value" />
<br />
Your number: <span id="mirror1"></span>
</td>
</tr>
<tr>
<td>
Email:
<input type = "text" id="userEmail"
name="email" onkeyup="document.getElementById('mirror2').innerHTML=this.value" />
<br />
Your email: <span id="mirror2"></span>
</td>
</tr>
<tr>
<td>
Gender:<br />
<input type="radio" name="gen" id="userGender" value="Decline"
checked/> Decline<br />
<input type="radio" name="gen" id="userGender" value="Male" />Male<br />
<input type="radio" name="gen" id="userGender" value="Female" /> Female
<tr>
<td>
Major:
<select name="major" id="userMajor">
<option value="" selected="selected">Select Major</option>
<option value="Computer Science">Computer Science</option>
<option value="Information Technology">Information Technology</option>
<option value="Engineering">Engineering</option>
<option value="Biology">Biology</option>
<option value="Other">Other</option>
</select>
</td>
</tr>
<tr>
<td>
Hobbies:<br />
<input name="hob" id="userHobby" type="checkbox" value="Running,
" + " " />Running<br />
<input name="hob" id="userHobby" type="checkbox" value="Sleeping,
" + " "/>Sleeping<br />
<input name="hob" id="userHobby" type="checkbox" value="Fishing,
" + " "/>Fishing<br />
<input name="hob" id="userHobby" type="checkbox" value="Other" />Other
</td>
</tr>
</table>
<p>
<input type="button" value="Enter" onclick="Survey()"/>
</p>
</form>
</div>
</form>
JavaScript:
function Survey()
{
if (!ValidateForm())
{
return false;
}
else {
var userName = document.forms[0].name.value+"<br />";
var userNumber = document.forms[0].number.value+"<br />";
var userEmail= document.forms[0].email.value+"<br />";
var sex;
if (document.forms[0].gen[0].checked)
sex=document.forms[0].gen[0].value;
else if (document.forms[0].gen[1].checked)
sex=document.forms[0].gen[1].value;
else if (document.forms[0].gen[2].checked)
sex=document.forms[0].gen[2].value;
var userGender = sex+"<br />";
var userMajor = document.forms[0].major.value+"<br />";
var hobby=new Array()
var counter=0;
for (i=0;i<document.forms[0].hob.length;i++)
{
if (document.forms[0].hob[i].checked)
{
hobby[counter]=document.forms[0].hob[i].value;
counter++;
}
}
var hobPick="";
for (n=0;n<hobby.length;n++)
hobPick+=hobby[n];
var userHobby = hobPick;
document.getElementById("printName").innerHTML = userName
document.getElementById("printNumber").innerHTML = userNumber
document.getElementById("printEmail").innerHTML = userEmail
document.getElementById("printGender").innerHTML = userGender
document.getElementById("printMajor").innerHTML = userMajor
document.getElementById("printHobby").innerHTML = userHobby
document.getElementById('formtext').submit();
}
}
function ValidateForm()
{
if (document.forms[0].name.value.length === 0)
{
alert("Name is Required");
return false;
}
else if
(document.forms[0].number.value.length === 0)
{
alert("Number is Required");
return false;
}
else if
(document.forms[0].email.value.length === 0)
{
alert("Email is Required");
return false;
}
else if
(document.forms[0].userMajor.value === "")
{
alert("Major is Required");
return false;
}
else if
(document.forms[0].userHobby[0].checked === false &&
document.forms[0].userHobby[1].checked=== false &&
document.forms[0].userHobby[2].checked === false &&
document.forms[0].userHobby[3].checked === false)
{
alert("hobby is Required");
return false;
}
else
{
return true;
}
}
PHP:
<table id='userInputTbl' width='600' border='1'>
<tr>
<td id='tblName' colspan='6'>
<strong>You Submitted: </strong><br />
</td>
</tr>
<tr>
<td><strong>Name:</strong><br />
</td>
<td> <?echo $_POST["printName"]?></td>
</tr>
<tr>
<td><strong>Number:</strong><br /></td>
<td> <?echo $_POST['printNumber']?></td>
</tr>
<tr>
<td><strong>Email:</strong><br /></td>
<td> <?echo $_POST['printEmail']?></td>
</tr>
<tr>
<td><strong>Gender:</strong><br /></td>
<td> <? echo $_POST['printGender']?></td>
</tr>
<tr>
<td><strong>Major:</strong><br /></td>
<td> <? echo $_POST['printMajor']?></td>
</tr>
<tr>
<td><strong>Hobbies:</strong><br /></td>
<td> <? echo $_POST['printHobby']?></td>
</tr>
</table>
Your problem lies in this part:
document.getElementById("printName").innerHTML = userName
document.getElementById("printNumber").innerHTML = userNumber
document.getElementById("printEmail").innerHTML = userEmail
document.getElementById("printGender").innerHTML = userGender
document.getElementById("printMajor").innerHTML = userMajor
document.getElementById("printHobby").innerHTML = userHobby
No such IDs exist! by the way , ID should be unique which means only one element should have userHobby as ID.
<td>
Hobbies:<br />
<input name="hob" id="userHobby" type="checkbox" value="Running,
" + " " />Running<br />
<input name="hob" id="userHobby" type="checkbox" value="Sleeping,
" + " "/>Sleeping<br />
<input name="hob" id="userHobby" type="checkbox" value="Fishing,
" + " "/>Fishing<br />
<input name="hob" id="userHobby" type="checkbox" value="Other" />Other
</td>
You seem to have an extra { in your ValidateForm() function:
{
var userName = document.forms[0].name.value+"<br />";
Perhaps you want to change it to:
else {
var userName = document.forms[0].name.value+"<br />";
Your php file is broken.
<?php
echo <table id='userInputTbl' width='600' border='1'>
<tr>
<td id='tblName' colspan='6'>
<strong>You Submitted: </strong><br />
</td>
</tr>
<tr>
<td><strong>Name:</strong><br />
</td>
<td <?echo $_POST["userName"]?> ></td>
echo expects a string, but you don't need any of that anyway.
Get rid of the opening <?php and the echo. Go right into the html like this
<table id='userInputTbl' width='600' border='1'>
<tr>
<td id='tblName' colspan='6'>
<strong>You Submitted: </strong><br />
</td>
</tr>
<tr>
<td><strong>Name:</strong><br />
</td>
<td <?echo $_POST["userName"]?> ></td>
This part also looks wrong:
<td <?echo $_POST["userName"]?> ></td>
I think you meant
<td><?echo $_POST["userName"]?></td>
Also, in this section:
function Survey()
{
if (!ValidateForm())
{
return false;
}
{
var userName = document.forms[0].name.value+"<br />";
The { is out of place. Do you mean to have an else { there?
And another thing: What is the point of displaying the values to the id="print..." elements if you're just submitting the form anyway? The user won't see any of it, just for a split second before they're redirected anyway. Get rid of all of that.
I'm back again...
You're inconsistent here:
document.forms[0].hob[i]
vs this:
document.forms[0].userHobby[0]
You should be using the names, not the ids, here. Use hob.
You must do this validation in the OnSubmit event of the form, see this article in W3Schools
Related
NOTHING IS WORKING! I added onSubmit = "validate()" to my register button in the form, and I made the function and the alert if the fields are left empty. But NOTHING IS WORKING!
No alerts no errors in console. No hope!
<head>
<title>WHAT THE TECH!</title>
<script type="text/javascript">
function validate() {
let fullname = document.getElemenyByname("full_name").value;
let email = document.getElemenyById("email").value;
let pass = document.getElemenyById("password").value;
let add = document.getElemenyById("address").value;
if (fullname == "" || fullname.length == 0) {
alert("Enter Full Name");
document.getElemenyById("full_name").focus;
return false;
} else if (email == "" || email.length == 0) {
alert("Enter Email Address!");
document.getElemenyById("email").focus;
return false;
}
}
</script>
</head>
<body>
<div class="mainwrap">
<div class="content">
<div class="SignUp">
<div class="Formup">
<div class="title">New here? Register!</div>
<form name="register">
<table>
<tr>
<td>Full Name: </td>
<td><input type="text" id="full_name">
</td>
</tr>
<tr>
<td>Email: </td>
<td><input type="text" id="email">
</td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password" id="password">
</td>
</tr>
<tr>
<td>Country: </td>
<td>
<select>
<option value="U.A.E">U.A.E</option>
<option value="K.S.A">K.S.A</option>
<option value="Qatar">Qatar</option>
</select>
</td>
</tr>
<tr>
<td>Gender: </td>
<td>
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</td>
</tr>
<tr>
<td>Address: </td>
<td><input type="text" id="address">
</td>
</tr>
<tr>
<td>
<input type="submit" value="Register" class="registerbutton" name="register" onSubmit="validate()">
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>
</body>
You should use document.getElementsByName if you want to fetch the value using name attribute. I would recommend to do it by "id" attribute.
function submitFunction() {
var firstName = document.getElementsByName("first_Name")[0].value;
if (firstName == "" || firstName == null || firstName.length == 0) {
alert("First Name is required");
return false;
}
}
Also add return to the onsubmit event to avoid page refresh.
<form name="Register" onsubmit="return submitFunction() " method="post">
Option 2 : Using HTML5
The required attribute will do the validation check and you can skip javascript.
<input type="text" name="first_Name" required>
I am new bee to JavaScript. I have a form which is not validated with alert button. I am having a form which is to be submitted without errors. If I submit the forms with the empty fields, an alert message should be popped up.
The following is my code:
function validate_Form() {
alert('hi how');
exit;
var tokenNo = document.forms["myForm"]["txt1"].tokenNo;
if (tokenNo == null || tokenNo == "") {
alert("Enter The Token No");
return false;
} else {
document.write("pola");
}
}
<table>
<form name="Sec_guard_form" onsubmit="validate_Form()">
<tr>
<td>Token No</td>
<td>
<input type="text" value="" name="token_no" />
</td>
</tr>
<tr>
<td>Other Property</td>
<td>
<input type="text" value="" name="other_prop" />
</td>
</tr>
<tr>
<td>Bike Number</td>
<td>
<input type="text" value="" name="bike_no" />
</td>
</tr>
<tr>
<td>bike name</td>
<td>
<input type="text" value="" name="bike_nm" />
</td>
</tr>
<tr>
<td>bike model</td>
<td>
<select option="bike model">
<option value="Activa 3G">Activa 3G</option>
<option value="shine">shine</option>
<option value="unicon">unicon</option>
<option value="yuga">yuga</option>
<option value="neo">neo</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" value="submit" />
</td>
<td>
<input type="submit" value="cancel" />
</td>
</tr>
</form>
</table>
The above is my code, for i am using the mozilla firefox as my browser. Is that an issue. My function inside the script is not even called. what am i wrong here...
You can change your javascript like this :
function validate_Form() {
var form = document.querySelector("form");
var tokenNo = form.elements.token_no.value;
if (tokenNo == null || tokenNo == "") {
alert("Enter The Token No");
return false;
} else {
document.write("pola");
}
return false;
}
and your html like this:
<form name="Sec_guard_form" onsubmit="return validate_Form()">
exit; doesn't mean anything in javascript. You have to use return. So if you return before the function does anything then it is not useful at all!
The syntax you used for selecting form element and getting its value was wrong according to me so I corrected the syntax...
Also, you might be wondering why to use return validate_form() in HTML and return false in the function. It is used just for stopping the page to refresh/redirect before the entire function gets executed!
Try this code, it worked for me... I don't know what hi how was for so I eliminated it.
You are not calling function on your submit button Please use this to call function first.
<input type="submit" value="submit" onclick="validate_Form()" />
change
<form name="Sec_guard_form" onsubmit="validate_Form()">
to
<form name="Sec_guard_form" onsubmit="return validate_Form()">
Complete html code
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<table>
<form id="Sec_guard_form" onsubmit="return validate_Form();" method="post">
<tr>
<td>Token No</td>
<td>
<input type="text" value="" name="token_no" />
</td>
</tr>
<tr>
<td>Other Property</td>
<td>
<input type="text" value="" name="other_prop" />
</td>
</tr>
<tr>
<td>Bike Number</td>
<td>
<input type="text" value="" name="bike_no" />
</td>
</tr>
<tr>
<td>bike name</td>
<td>
<input type="text" value="" name="bike_nm" />
</td>
</tr>
<tr>
<td>bike model</td>
<td>
<select option="bike model">
<option value="Activa 3G">Activa 3G</option>
<option value="shine">shine</option>
<option value="unicon">unicon</option>
<option value="yuga">yuga</option>
<option value="neo">neo</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="submit" value="submit" />
</td>
<td>
<input type="submit" value="cancel" />
</td>
</tr>
</form>
</table>
<script>
function validate_Form()
{ alert('hi how');
var tokenNo = document.getElementById("Sec_guard_form")["token_no"].value;
if (tokenNo == null || tokenNo == "")
{
alert("Enter The Token No");
return false;
}
else
{
document.write("pola");
}
}
</script>
</body>
</html>
This is working fine
I have all of my validation code figured
out but I'm not quite sure on how to code an
alert to pop up before the form is submitted
but after the validation is complete. Pretty
much my alerts which fields have errors, and
what the errors are aren't showing up when
I submit this form. All it is direct me to the
submit successful page despite errors.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<script>
function validateForm() {
var fName = document.forms["orderForm"].firstName.value;//first name validation
if(fName==null || fName=="")
{
document.getElementById('firstNameError').innerHTML= "Please enter a first name.";
return false;
}
var lName = document.forms["orderForm"].lastName.value;//last name validation
if(lName==null || lName=="")
{
document.getElementById('lastNameError').innerHTML= "Please enter a last name.";
return false;
}
var address = document.forms["orderForm"].address.value;//address validation
if(address==null || address=="")
{
document.getElementById('addressError').innerHTML= "Please enter an address.";
return false;
}
var city = document.forms["orderForm"].city.value;//city validation
if(city==null || city=="")
{
document.getElementById('cityError').innerHTML= "Please enter a city.";
return false;
}
var pCodeCheck = /^[0-9a-zA-Z]+$/;//postal code validation
if(postalCode.value.match(pCodeCheck))
{
//do nothing
return true;
}
else
{
document.getElementById('postalCoderror').innerHTML= "Please enter a valid postal code.";
return false;
}
// 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.";
return false;
}
var itemQTY2 = document.forms["orderForm"].widget2qty.value;
if(itemQTY2 < 0)
{
document.getElementById('qtyError2').innerHTML= "You cannot enter a negative number.";
return false;
}
var itemQTY3 = document.forms["orderForm"].widget3qty.value;
if(itemQTY3 < 0)
{
document.getElementById('qtyError3').innerHTML= "You cannot enter a negative number.";
return false;
}
//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.";
return false;
}
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;
}
function startValidate(){
validateForm();
document.forms['orderForm'].submit();
}
</script>
<div id="wrapper">
<h2 class="center">Order Form</h2> <!-- action="processForm.html" "javascript:void(0)" -->
<form name="orderForm" method="post" onsubmit="validate();" action="processForm.html">
<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">Québec</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></tr><tr></tr><tr></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" onsubmit="startValidate()" value="Submit Order">
<td><input type="reset" name="btnReset" id="btnReset" value="Reset Form"></td>
</tr>
</table>
</fieldset>
</form>
</div>
</body>
This is what I would do:
HTML:
<body>
<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">Québec</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></tr><tr></tr><tr></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>
JS:
<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 (postalCode.value.match(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>
you need to have
<form name="orderForm" method="post" onsubmit="return validate();">
than
<form name="orderForm" method="post" onsubmit="validate();">
The "return" part of it makes sure javascript returns the true/false value and does whatever necessary action is needed
and also in your script try having a one boolean variable that acts as a control so that for example "valid" if 9/10 are correct, the boolean value valid will be false and then the form will not submit.
Example below
function validateForm() {
var valid = new Boolean(true);
//code here - example
var fName = document.forms["orderForm"].firstName.value;//first name validation
if(fName==null || fName=="")
{
valid = false;
document.getElementById('firstNameError').innerHTML= "Please enter a first name.";
return false;
}
return valid
}
There is no use of startValidate function. Just remove that.
your form tag should be <form name="orderForm" method="post" onsubmit="return validateForm();" action="processForm.html">
Use this as submit button, <input type="submit" name="btnSubmit" id="btnSubmit" value="Submit Order"> //<- removed onsubmit="startValidate()" as this is not required.
Most important, just validate your HTML before posting here.
Use onsubmit="startValidate();"
<form name="orderForm" method="post" onsubmit="startValidate();" action="processForm.html">
You can simply use the jQuery Validate plugin as follows.
jQuery:
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}
});
});
HTML:
<form id="myform">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" />
</form>
When you call startValidate() it will kick off the document.forms.submit line whether or not the validateForm() returns true or false. You need to only submit the form if validateForm() returns true. A false return in your validator won't kill the startValidate() function like you are thinking it will.
Try moving the document.forms['orderForm'].submit(); up into the bottom of your validateForm() method after you've checked all the inputs.
<table>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>
<input type="text" class="textbox" value="Not Required" readonly=readonly />
</td>
<td>
<input type="checkbox" onclick="CheckCheckboxes1(this)"/>
</td>
</tr>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>
<input type="text" class="textbox" value="Not Required" readonly/>
</td>
<td>
<input type="checkbox" onclick="CheckCheckboxes1(this)" />
</td>
</tr>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>
<input type="text" class="textbox" value="Not Required" readonly/>
</td>
<td>
<input type="checkbox" onclick="CheckCheckboxes1(this)" />
</td>
</tr>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>
<input type="text" class="textbox" value="Not Required" readonly/>
</td>
<td>
<input type="checkbox" onclick="myFunction(this)" />
</td>
</tr>
</table>
I want to clear textbox when we corresponding checkboc is checked. Here is my Java script,
<script type="text/javascript" language="javascript">
function CheckCheckboxes1(chk){
if(chk.checked == true)
{
var txt = document.getElementById('TextBox1');
txt.value = "";
txt.disabled = false;
}
else
{
var txt = document.getElementById('TextBox1');
txt.value = "Enter Username";
txt.disabled = true;
}
}
</script>
Any idea?
In order to get the corresponding textbox, you can't get it by ID. Instead you should get the inputs parent table row and then find the input from there, so that it is relative to the checkbox.
Working demo
function CheckCheckboxes1(chk){
var txt = chk.parentNode.parentNode.cells[2].getElementsByTagName('input')[0];
if(chk.checked == true)
{
txt.value = "";
txt.readOnly = false;
}
else
{
txt.value = "Enter Username";
txt.readOnly = true;
}
}
Notes:
Use txt.readOnly not txt.disabled because disabled is something different.
Use the checkbox onchange event not onclick.
Hi in order to disable and enable you need to assign the id's to both checkbox and textboxs. please look at the below code.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" language="javascript">
function CheckCheckboxes1(chk){
if(chk.checked == true)
{
var txt = document.getElementById('TextBox'+chk.id);
txt.value = "";
txt.disabled = false;
}
else
{
var txt = document.getElementById('TextBox'+chk.id);
txt.value = "Enter Username";
txt.disabled = true;
}
}
</script>
</head>
<body>
<table>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>
<input type="text" id= "TextBox1" class="textbox" value="Not Required" readonly=readonly />
</td>
<td>
<input type="checkbox" id="1" onclick="CheckCheckboxes1(this)"/>
</td>
</tr>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>
<input type="text" id= "TextBox2" class="textbox" value="Not Required" readonly/>
</td>
<td>
<input type="checkbox" id="2" onclick="CheckCheckboxes1(this)" />
</td>
</tr>
<tr>`enter code here`
<td>Value1</td>
<td>Value2</td>
<td>
<input type="text" id= "TextBox3" class="textbox" value="Not Required" readonly/>
</td>
<td>
<input type="checkbox" id="3" onclick="CheckCheckboxes1(this)" />
</td>
</tr>
<tr>
<td>Value1</td>
<td>Value2</td>
<td>
<input type="text" id= "TextBox4" class="textbox" value="Not Required" readonly/>
</td>
<td>
<input type="checkbox" id="4" onclick="myFunction(this)" />
</td>
</tr>
</table>
</body>
</html>
As #Adil said it is easier if you use jQuery. You can give your textbox an id and your checkbox a cutstom attribute e.g.:
<td>
<input type="text" id="txt_1" class="textbox" value="Not Required" readonly=readonly />
</td>
<td>
<input type="checkbox" specId="1" onclick="CheckCheckboxes1(this)"/>
</td>
function CheckCheckboxes1(chk){
var specId = $(chk).attr("specId");
var txt = $("#txt_"+specId);
if(chk.checked == true)
{
$(txt).val("");
$(txt).attr("disabled","disabled");
}
else
{
$(txt).val("Enter Username");
$(txt).removeAttr("disabled");
}
}
Hope it helps!
I am performing JavaScript validation on a simple HTML page. On error I am trying to redirect the page to Error.html, using window.location.href="Error.html".
I get the JavaScript pop displaying the error but page doesn't redirect.
JS:
function checkifFormIsFilled() {
var txtUserName = document.getElementById("txtUserName").value;
var txtFirstName = document.getElementById("txtFirstName").value;
var txtLastName = document.getElementById("txtLastName").value;
var txtEmail = document.getElementById("txtEmail").value;
var txtArea = document.getElementById("txtArea").value;
var errMessage = "";
var errorInForm = false;
if (txtUserName === "") {
errMessage = "UserName";
errorInForm = true;
}
if (txtFirstName === "") {
errMessage += ", First Name";
errorInForm = true;
}
if (txtLastName === "") {
errMessage += ", Last Name";
errorInForm = true;
}
if (txtEmail === "") {
errMessage += ", Email";
errorInForm = true;
}
if (txtArea === "") {
errMessage += ", Address";
errorInForm = true;
}
if (errorInForm == true) {
errMessage += " are required fields";
window.alert(errMessage);
//window.location.href = "Error.html";
window.navigate("Error.html");
}
}
HTML:
<form method="post" style="width: 560px; height: 850px; margin-left: 10px; margin-top:10px">
<fieldset>
<legend>New User</legend>
<table>
<tr>
<td>
<label>User Name:</label></td>
<td>
<input type="text" id="txtUserName" name="User Name" onblur="checkRequired(this)" maxlength="10" /></td>
</tr>
<tr>
<td>
<label>First Name:</label></td>
<td>
<input type="text" id="txtFirstName" name="First Name" maxlength="10" onblur="checkRequired(this)" /></td>
</tr>
<tr>
<td>
<label>Last Name:</label></td>
<td>
<input type="text" id="txtLastName" name="Last Name" maxlength="10" onblur="checkRequired(this)" /></td>
</tr>
<tr>
<td>
<label>Email: </label>
</td>
<td>
<input type="text" name="emailInput" id="txtEmail" onblur="checkRequired(this)" /></td>
</tr>
<tr>
<td>
<label for="lblAddress">Address</label></td>
<td>
<textarea id="txtArea" name="txtAddress" cols="50" rows="5" maxlength="1000" onblur="checkRequired(this)"></textarea></td>
</tr>
<tr>
<td>Groups</td>
<td>
<select name="selGroups">
<option value="c1">Employee</option>
<option value="c1">HR</option>
<option value="c1">Director</option>
</select>
</td>
</tr>
<tr>
<td>Status</td>
<td>
<select name="selStatus">
<option value="c1">Active</option>
<option value="c2">Inactive</option>
</select>
</td>
</tr>
<tr>
<td>
<input id="btnSubmit" value="Add User" type="submit" onclick="checkifFormIsFilled();" />
</td>
<td>
<button id="btnCancel">Cancel</button>
</td>
</tr>
</table>
</fieldset>
</form>
This should do:
if (errorInForm == true) {
errMessage += " are required fields";
window.alert(errMessage);
window.location = "Error.html";
}
Put the function call in an onsubmit attribute on the form element instead. You may also have to return false as well, if an error was found, to prevent it from going to the same page instead of your error page.
Try this:
<input id="btnSubmit" value="Add User" type="button" onclick="checkifFormIsFilled();" />
Since the form was submitting to itself, the redirect wasn't occurring.
DEMO