validate forms with js - javascript

Hi I had my script working then I ran it through w3 validator and changed what I told me was wrong and now it stops validating at the first postcode, I have stuffed up and cant remember what was changed bigg lesson learnt do 1 thing at a time, I have been pulling my hair out trying to get it working again but cant figure out how if any 1 can take to time to look at it, I would greatly appreciate it, thanks
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Joes Fruit and Vegetable Store</title>
<script>
//calender dropdown menu
var monthtext = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
function populatedropdown(dayfield, monthfield, yearfield) {
var today = new Date()
var dayfield = document.getElementById(dayfield)
var monthfield = document.getElementById(monthfield)
var yearfield = document.getElementById(yearfield)
for (var i = 0; i < 31; i++)
dayfield.options[i] = new Option(i, i + 1)
dayfield.options[today.getDate()] = new Option(today.getDate(), today.getDate(), true, true) //select today's day
for (var m = 0; m < 12; m++)
monthfield.options[m] = new Option(monthtext[m], monthtext[m])
monthfield.options[today.getMonth()] = new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
var thisyear = today.getFullYear()
for (var y = 0; y < 20; y++) {
yearfield.options[y] = new Option(thisyear, thisyear)
thisyear += 1
}
yearfield.options[0] = new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
}
// function validate
function validate_form() {
valid = true;
// validate name
/* if ( document.input.name.value == "" )
{
alert ( "Please enter your name" );
valid = false;
}
// validate address
if ( document.input.address.value == "" )
{
alert ( "Please enter your address address" );
valid = false;
}
// validate suburb town
if ( document.input.town.value == "" )
{
alert ( "Please enter your Suburb or town" );
valid = false;
}
// validate postcode
var y = document.getElementById("postcode").value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Postcode must be in numbers.");
document.getElementById("postcode").focus();
return false;
}
if (y.length>4 || y.length<4)
{
alert("Postcode should be 4 digit");
document.getElementById("postcode").focus();
return false;
}
*/
// validate home phone
var y = document.getElementById('hphone').value;
if (isNaN(y) || y.indexOf(" ") != -1) {
alert("Home Phone number must be in numbers.");
document.getElementById('hphone').focus();
return false;
}
if (y.length > 10 || y.length < 10) {
alert("Home Phone number should be 10 digit");
document.getElementById('hphone').focus();
return false;
}
// validate work phone
var y = document.getElementById('wphone').value;
if (isNaN(y) || y.indexOf(" ") != -1) {
alert("work Phone number must be in numbers.");
document.getElementById('wphone').focus();
return false;
}
if (y.length > 10 || y.length < 10) {
alert("Work Phone number should be 10 digit");
document.getElementById('wphone').focus();
return false;
}
// validate fax
var y = document.getElementById('fax').value;
if (isNaN(y) || y.indexOf(" ") != -1) {
alert("Fax number must be in numbers.");
document.getElementById('fax').focus();
return false;
}
if (y.length > 10 || y.length < 10) {
alert("Fax Phone number should be 10 digit");
document.getElementById('fax').focus();
return false;
}
// validate email
{
var x = document.forms["input"]["email"].value;
var atpos = x.indexOf("#");
var dotpos = x.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
alert("Not a valid e-mail address");
return false;
}
}
// validate radio buttons
var o = document.getElementById('rad1');
var t = document.getElementById('rad2');
if ((o.checked == false) && (t.checked == true)) {
// validate alternative address
if (document.input.street.value == "") {
alert("Please enter alternative address address");
valid = false;
}
// validate suburb town
if (document.input.suburb.value == "") {
alert("Please enter alternative Suburb or town");
valid = false;
}
} // validate postcode
var y = document.getElementById('postcode2').value;
if (isNaN(y) || y.indexOf(" ") != -1) {
alert("Postcode must be in numbers.");
document.getElementById('postcode2').focus();
return false;
}
if (y.length > 4 || y.length < 4) {
alert("Alternative Postcode should be 4 digit");
document.getElementById('postcode2').focus();
return false;
}
// validate message box
var o = document.getElementById('card');
if ((o.checked == true)) {
if (document.input.message.value == "") {
alert("Please enter message");
valid = false;
}
return valid;
}
}
</script>
</head>
<body> <b>Order form for Joe's Fruit Shop</B><br><br>
<b> * means you must fill in the details.</B><br><br>
<b>Your details:</b>
<br>
<br>
<!-- Beggining of Form -->
<form name="input" action="cal2.html" onsubmit="validate_form ()">
<!--name form -->* Name:
<input type="text" name="name" onclick="this.value='';" value="Enter your name with first">
<br>
<br>
<!-- Address form -->* Address:
<input type="text" name="address" onclick="this.value='';" value="Enter your street address">
<br>
<br>
<!-- Suburb state dropdown form-->* Suburb or Town:
<input type="text" name="town" onclick="this.value='';"
value="suburb">State:
<select name="state">
<option value="NSW">NSW</option>
<option selected="selected" value="QLD">QLD</option>
<option value="SA">SA</option>
<option value="WA">WA</option>
<option value="TAS">TAS</option>
<option value="VIC">VIC</option>
<option value="NT">NT</option>
<option value="ACT">ACT</option>
</select>
<!-- post code form -->* Postcode:
<input type=text name="postcode" onclick="this.value='';" value="****">
<br>
<br>
<!-- Home phone form-->* Phone:
<input type=text name="hphone" onclick="this.value='';" value="x-xxxx-xxx">
<!-- work phone form -->Work phone
<input type=text name="wphone" onclick="this.value='';" value="x-xxxx-xxx">
<br>
<br>
<!-- Fax form-->*Fax:
<input type=text name="fax" onclick="this.value='';" value="0x-xxxx-xxx">
<!-- Email form-->Email address:
<input type=text name="email" onclick="this.value='';" onsubmit="return validateForm();"
value="Enter your current email">
<br>
<br>
<br>
<!-- credit card--> <b>Credit card details:</b>
<br>
<br>* Type:
<select name="credit card">
<option selected="selected" value="AMEX">Amex</option>
<option value="Visa">Visa</option>
<option value="Mastercard">Mastercard</option>
</select>*Expiry date:
<select name="expiration_month">
<option value="">Choose...</option>
<option selected="selected" value="1">January</option>
<option value="2">Febuary</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select name="expiration_year">
<option value="">Choose...</option>
<option selected="selected" value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
</select>
<br>
<br>
<B>Purchase details</B><br><br> <!-- Product dropdown form-->
* Product:
<select name="product">
<option value="carrot">Bag of carrots</option>
<option value="zucchini">Zucchini</option>
<option value="cabbage">Cabbage</option>
<option value="grapes">Grapes</option>
<option value="tomatoes">TAS</option>
<option value="apples">Apples</option>
<option value="banana">banana</option>
<option selected="selected" value="cucumber">Cucumber</option>
</select>
<!-- Quantity dropdown form-->
Quantity:
<select name="quantity">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
</select>
<br><br><br>
* <B>Deliver to:</B>
<br><br>
<!-- Address Radio buttons-->
<input type='radio' id="rad1" name='radio' value='Home address' checked="checked">Home Address<br>
<input type='radio' id="rad2" name='radio' value='Other address'/>Other Address<br><br>
<!--other address-->
<!-- street form-->
Street <input type=text name="street" onclick="this.value='';" value="Street"><br><br>
<!-- Suburb form-->
Suburb <input type=text name="suburb" onclick="this.value='';" value="Suburb or town"><br><br>
<!-- State dropdown form-->
State <select name="state">
<option value="NSW">NSW</option>
<option selected="selected" value="QLD">QLD</option>
<option value="SA">SA</option>
<option value="WA">WA</option>
<option value="TAS">TAS</option>
<option value="VIC">VIC</option>
<option value="NT">NT</option>
<option value="ACT">ACT</option>
</select><br><br>
<!-- post code form -->
Postcode:<input type=text name="postcode2" onclick="this.value='';" value="****"><br><br><br>
* Date delivery required:
<!-- Calender drop down menu-->
<select id="daydropdown">
</select>
<select id="monthdropdown">
</select>
<select id="yeardropdown">
</select>
<script type="text/javascript">
//populatedropdown(id_of_day_select, id_of_month_select, id_of_year_select)
window.onload=function(){
populatedropdown("daydropdown", "monthdropdown", "yeardropdown")
}
</script>
<br><br>
<!-- include a card option-->
Include a card: <input type="checkbox" name="card" value="Yes">Yes<br><br>
Personal message on card: <textarea rows="10" name="message" cols="30" onclick="this.value='';" >Enter your personal message here</textarea><br><br>
Click on <b>Submit</b> when done; click on <b> Clear form</b> to reset.
<!-- submit button-->
<input type="submit" value="Submit">
<!-- reset button-->
<input type="reset" value="Reset">
</form>
</body>
</html>

Your scripts are failing as you are trying to get elements by Id and checking the value property of a null.
var y = document.getElementById('hphone').value;
This throws an exception and exits, the form then submits
Give your elements Ids to match the name attribute and it should be okay
<input type=text name="hphone" id="hphone" onclick="this.value='';" value="x-xxxx-xxx">
change your onsubmit attribute to the follow to cancel the submit on validation error
<form name="input" action="cal2.html" onsubmit="return validate_form ()">
To check against a default value, you could added a data attribute and cross check the value in the validation.
* Phone: <input type=text name="hphone" id="hphone" onclick="this.value='';" data-default="x-xxxx-xxx" value="x-xxxx-xxx">
var element = document.getElementById('hphone');
var y = element.value;
var defValue = element.attributes["data-default"].value;
if(isNaN(y)||y.indexOf(" ")!=-1|| y === defValue )
{
alert("Home Phone number must be in numbers.");
document.getElementById('hphone').focus();
return false;
}
If you are targetting HTML5 compliant browsers you could use the placeholder attribute.
http://www.w3schools.com/html5/att_input_placeholder.asp

Related

How can I link two pages through JavaScript?

I created two webpages and I want to connect them...except through JavaScript (I know how to do it in HTML) the first page is supposed to act almost like a password screen to prevent under aged users from entering. I have created a rough code but I don't know how to make them link properly. Here's what I've got so far:
<!DOCTYPE html>
<html>
<head>
<!-- this is how you add a code comment-->
<title> Entrance Page </title>
</head>
<body bgcolor="#CEF6F5">
<form>
<h2 align=center><u> Please fill out the following information to proceed to the festival: </u></h2>
<br><br>First Name:<input type="text" name="First Name" id="first"> Last Name:<input type="text"
name="Last Name" id="last">
<br><br> age:<select name="age" id="age">
<option value="1"> below 10 </option>
<option value="2"> 10 </option>
<option value="3"> 11 </option>
<option value="4"> 12 </option>
<option value="5"> 13 </option>
<option value="6"> 14 </option>
<option value="7"> 15 </option>
<option value="8"> 16 </option>
<option value="9"> 17 </option>
<option value="10"> 18 </option>
<option value="11"> 19 </option>
<option value="12"> 20 </option>
<option value="13"> above 20 </option>
</select>
</form>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<p align="center"> <button type="submit" onclick="run()"> Submit </button> </p>
<p><p id="p1"> </p>
<script>
var firstName = document.getElementById("first").value
var lastName = document.getElementById("last").value
var age = document.getElementById("age").value
var isNum = " ";
isNum = isNum + isNaN(firstName)
function run () {
var firstName = document.getElementById("first").value
var lastName = document.getElementById("last").value
if (age < 10 ) {
window.alert("your too young to enter in this event!")//go back to Entrance page
} else if (age > 10) {
window.alert("welcome to the Oktoberfest website!");
document.getElementById("pass").value//go to main website
} else if (age == 10) {
window.alert("lucky! you are just barely old enough to join!")
document.getElementById("pass").value//go to main website
}
}
if (isNum == true) {
window.alert("your name cannot be a number");
}//go back to Entrance page
while (firstName.length ==0) {
window.alert ("you didn't enter a first name ")
document.getElementById("block").value//go back to Entrance page
while (lastNamet.length ==0) {
window.alert ("you didn't enter a last name ")
document.getElementById("block").value//go back to Entrance page
</script>
</body>
</html>
You can do :
window.location.href = "your-next-page.html";
//or
window.location.replace("your-next-page.html");

Check out form to calculate total cost of items

So I am making an ecommerce style website where people can purchase smartphones. In this website I have a checkout form where users can select what phone they wish to choose and then depending on the quantity the form displays the total cost for the user. However since I am using drop down options I am not sure on how to go about getting the value of the phone, multiplying it by the quantity and displaying the total cost at the bottom.
div class="contact-wrap">
<div class="title-box">
<b>Check Out</b>
</div>
<div id="form1">
<img id="phone" src="iphone6.jpg" width="294" height="320"/>
<select id="phoneList">
<option value="iphone1.jpg">Apple iPhone 11 Pro Max (2019) 512GB Silver</option>
<option value="iphone2.jpg">Apple iPhone 11 (2019) 128GB Black</option>
<option value="iphone3.jpg">Apple iPhone 11 (2019) 256GB White</option>
</select>
<select id="quantity">
<p>Quantity</p>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</div>
<div id="form2">
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
<p>First name: </p><input type="text" name="fname">
<p>Last name: </p><input type="text" name="lname">
<p>Email address: </p><textarea id="email" rows = "1" cols = "40" name="email"></textarea>
<p>Shipping address </p><textarea id="shipping" rows = "6" cols = "40" name="shipping"></textarea><br>
<input style="float:bottom; margin-top:20px" type="submit" value="Order">
</form>
</div>
</div>
<script>
function setPhone() {
var img = document.getElementById("phone");
img.src = this.value;
return false;
}
document.getElementById("phoneList").onchange = setPhone;
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
var y = document.forms["myForm"]["lname"].value;
var email = document.forms["myForm"]["email"].value;
var shipping = document.forms["myForm"]["shipping"].value;
if (x == "") {
alert("First name must be filled out");
return false;
}
else if (y == "") {
alert("Last name must be filled out");
return false;
}
else if (parseInt("0"+x, 10) > 0 || parseInt("0"+y, 10) > 0){
alert("Numbers not permissable for name");
return false;
}
else if (email == "") {
alert("Email must be filled out");
return false;
}
else if (shipping == "") {
alert("Shipping address must be filled out");
return false;
}
}
</script>
Doing some slight edits of your select to include attributes so it looks as follows:
<select id="phoneList">
<option value="iphone1.jpg" data-cost="100">Apple iPhone 11 Pro Max (2019) 512GB Silver</option>
<option value="iphone2.jpg" data-cost="200">Apple iPhone 11 (2019) 128GB Black</option>
<option value="iphone3.jpg" data-cost="300">Apple iPhone 11 (2019) 256GB White</option>
</select>
Then by getting the selected index and the data-cost defined above using
var i = phoneList.selectedIndex;
var phoneCost = document.getElementById("phoneList").getElementsByTagName("option")[i].getAttribute("data-cost");
you can get the cost of the selected phone.
Then just multiply the cost of the phone by the quantity from
document.getElementById("quantity").value;
and display it somewhere on your page.
So when the user selects an option in the dropdown call a function along the lines of
<script>
function CalcCosts() {
//Get user selected items
var i = phoneList.selectedIndex;
var phonecost = document.getElementById("phoneList").getElementsByTagName("option")[i].getAttribute("data-cost");
var quantity = parseInt(document.getElementById("quantity").value);
//Display on page
document.getElementById("PLACETODISPLAY").innerHTML = phonecost * quantity;
}
</script>
You could call the function using the onclick of the dropdowns as follows
<select id="quantity" onclick="CalcCosts()">
<p>Quantity</p>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
Edit:
Include suggestions from comments.

How do you use a select box input for a calculation? HTML and JS

How do I go about getting an amount from a selected drop down box? For instance
var alertMessage = 'Thanks for the order ' + field1 + ' ' + field2 + '. Your total is $' + String(parseInt() * parseInt()) + '.00.';
alert(alertMessage);
Select a product:
<br>
<select id="productselection">
<option value="blank"></option>
<option value="5">Widget 1</option>
<option value="10">Widget 2</option>
</select>
<br>Select a quantitiy:
<br>
<select id="quantityselection">
<option value="blank"></option>
<option value="5">5</option>
<option value="10">10</option>
</select>
<br>Select a Shipping Method:
<br>
<select id="shippingselection">
<option value="blank"></option>
<option value="0">Standard - Free</option>
<option value="10">3 day - $10</option>
<option value="25">Next Day - $25</option>
</select>
I need to calculate an order total with the following constraints
a select box which incorporates a shipping method selection (values should be Standard - free; 3-day - $10; and Next Day - $25)
add 7% sales tax to any order.
Widget 1 is worth $5
Widget 2 is worth $10
I need it to take widget 1 or 2s cash value and multiply it by the quanitity selected, for this case lets just say 5, or 10. It then will add another amount for the shipping cost that is selected. With that it will add a tax of 7% and then sends you and alert message with final cost. I already have part of the final message started from my other code. In the below code field 1 and field 2 are the customers first and last name.
This is what I am trying to implement this for
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css"> <!-- links stylesheet -->
<h1>JS Order Form</h1> <!-- Heading -->
</head>
<body>
<script src="script.js"> <!--links js -->
</script>
<div align="center">
<form id="myForm">
<fieldset>
<legend>Personal Information:</legend> <!-- first Form with first and last name-->
First Name: <input type="text" id="field1" name="fname"><br><br>
Last Name: <input type="text" id="field2" name="lname"><br>
</fieldset>
</form>
</div>
<br>
<div align="center">
<form id="myForm1"> <!-- form 2-->
<fieldset>
<legend>Order Info:</legend>
<table style="width:100%">
<table align="left"> <!-- Setting table constraints-->
<table border="1">
<tr>
<td>Product</td>
<td>Price</td>
</tr>
<tr>
<td>Widget 1</td> <!-- table contents-->
<td>$5</td>
</tr>
<tr>
<td>Widget 2</td>
<td>$10</td>
</tr>
</table>
<br>
<!-- form 2 with price and quanitity-->
<!--Price : <input type="text" id="field3" name="pname"><br><br>
Quantity: <input type="text" id="field4" name="qname"><br> -->
Select a product:<br>
<select id="productselection">
<option value="blank"></option>
<option value="5">Widget 1</option>
<option value="10">Widget 2</option>
</select>
<br>
Select a quantitiy:<br>
<select id="quantityselection">
<option value="blank"></option>
<option value="5">5</option>
<option value="10">10</option>
</select>
<br>
Select a Shipping Method:<br>
<select id="shippingselection">
<option value="blank"></option>
<option value="0">Standard - Free</option>
<option value="10">3 day - $10</option>
<option value="25">Next Day - $25 2</option>
</select>
</div>
</fieldset>
</form>
<div align="center">
<input type="button" onclick="myFunction();myFunction2() ;blankElement('productselection') ;blankElement('shippingselection') ;blankElement('quantityselection');" value="Clear"> <!-- submit and clear buttons-->
<input type="button" onclick="myFunction1()" value="Order">
</div>
function myFunction() {
document.getElementById("myForm").reset(); //grabs form and clears entrys
}
function myFunction2() {
document.getElementById("myForm1").reset(); // clears bottom form
}
function blankElement(id)
{
var element = document.getElementById(id);
element.value = blank;
}
function myFunction1()
{
var field1 = document.getElementById("field1").value.trim();
var field1Valid= true;
var field2 = document.getElementById("field2").value.trim(); // checks to see that a value is inputed
var field2Valid= true;
if ( field1.length == 0)
{
field1Valid= false;
} // the following checks to see if anything is inputed and returns a true or false/yes or no
if ( field2.length == 0)
{
field2Valid= false;
}
var formValid= field1Valid && field2Valid && field3Valid && field4Valid; //true if all fields are valid else false
if( !formValid){
var alertMessage= 'Please fill in the following '; //sets a var alert message if it meets criteria
if( !field1Valid){ alertMessage+= '[First Name] '; }
if( !field2Valid){ alertMessage+= '[Last Name] '; } // adds the following fields to the alert if they did not meet criteria of being full
alert(alertMessage);
return false;
}
else{
var alertMessage= 'Thanks for the order '+ field1+ ' '+ field2+ '. Your total is $'+ String(parseInt() * parseInt() )+ '.00.';
alert(alertMessage);
return true; // pushes out alert message by using field1 and field 2 and then multipling field 3 and 4 together to get a total
}
}
</body>
</html>
Check the below answer.
function Calculate() {
var f1 = document.getElementById("productselection");
var field1 = parseInt(f1.options[f1.selectedIndex].value);
var f2 = document.getElementById("quantityselection");
var field2 = parseInt(f2.options[f2.selectedIndex].value);
var alertMessage = 'Thanks for the order ' + field1 + ' x ' + field2 + '. Your total is $' + (field1 * field2).toFixed(2);
alert(alertMessage);
}
Select a product:
<br>
<select id="productselection">
<option value="blank"></option>
<option value="5">Widget 1</option>
<option value="10">Widget 2</option>
</select>
<br>Select a quantitiy:
<br>
<select id="quantityselection">
<option value="blank"></option>
<option value="5">5</option>
<option value="10">10</option>
</select>
<br>Select a Shipping Method:
<br>
<select id="shippingselection">
<option value="blank"></option>
<option value="0">Standard - Free</option>
<option value="10">3 day - $10</option>
<option value="25">Next Day - $25</option>
</select>
<br>
<br>
<button type="button" onClick="Calculate()">Calculate</button>

JavaScript Form Validation not working entirely

I am trying to have JavaScript code validate all the elements of this form but for some reason the select box doesn't validated. The user can fill in all the blanks except for the select box and the JavaScript does not catch it. Any ideas as to what I am missing? Thanks.
<script type="text/javascript">
function validateForm() {
var ageErr = document.getElementById('ageErr');
var nameErr = document.getElementById('nameErr');
var radioErr = document.getElementById('radioErr');
var results = document.getElementById('results');
var theName = document.formContact.theName;
var theAge = document.formContact.theAge;
var theRadioGp = document.formContact.contact;
var theSelect = document.formContact.theSelect;
var chkValue;
if(theName.value =="") {
nameErr.innerHTML = "A name is required ";
theName.focus();
return false;
}else {
nameErr.innerHTML= "";
}
if(theAge.value ==""){
ageErr.innerHTML = "An age is required";
theAge.focus();
return false;
}else {
nameErr.innerHTML = "";
}
if(theAge.vale =="") {
age.Err.innerHTML = "An age is required";
theAge.focus();
return false;
} else if (isNaN(theAge.value)) {
ageErr.innerHTML = "Age should be a number";
theAge.select();
} else if (theAge.value < 3 || theAge.value > 120) {
ageErr.innerHTML = "Please enter your real Age";
theAge.select();
return false;
} else{
ageErr.innerHTML = "";
}
for(var i=0; i < theRadioGp.length; i++) {
if(theRadioGp[i].checked ==true) {
chkValue = theRadioGp[i].value;
}
}
if(chkValue == undefined) {
alert('You need to slect a method of contact');
return false;
}
if(theSelect.options[theSelect.selectedIndex].text == "<--PLEASE SELECT ONE-->")
{alert("You need to select an option");
return false;
}else {
alert("Your have selected "+theSelect.options[theSelect.selectedIndex].text);
}
alert("Your form has been completed. Great Job!!");
}
</script>
</head>
<body>
<form action="" id="formContact" method="post" onsubmit="return validateForm();" name="formContact">
<p>Name:<br />
<input type="text" name="theName"><span class="err" id="nameErr"></span>
</p>
<p>Age:<br />
<input type="text" name="theAge"><span class="err" id="ageErr"></span>
</p>
<p>
<p>How may we contact you?<br>
<input type="radio" name="contact" value="email">Email<br>
<input type="radio" name="contact" value="no contact">No Contact<br>
</p>
<p>Please coose a selection below:<br>
<select name="theSelect">
<option><--PLEASE SELECT ONE -->
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</p>
<p><input type="submit" value="Submit" name="btnSubmit" ">
</form>
<span id="results"></span>
</body>
</html>
Your HTML isn't valid. Replace your select part with following
<select name="theSelect">
<option><--PLEASE SELECT ONE--></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Or use a numeric value for the default option
<select name="theSelect">
<option value="0">PLEASE SELECT AN OPTION</option>
<option value="1">One</option>
...
</select>
And check the value (not the text selected)
if(theSelect.options[theSelect.selectedIndex].value == 0){
alert("You need to select an option");
return false;
}else {
alert("Your have selected " + theSelect.options[theSelect.selectedIndex].text);
}
Why not use selectedIndex without the text?
Example:
<select id="mytest">
<option value="-1"><--PLEASE SELECT ONE--></option>
<option value="1">Test One</option>
<option value="2">Test Two</option>
</select>
Then
if(theSelect.selectedIndex == -1)
{alert("You need to select an option");
return false;
}else {
the rest

Form not validating before Submit (JavaScript)

I have a form written in JavaScript that works correctly when I submit. However, there is one conditional which I would like to be validated before the user hits the submit button. If the user chooses "None" on the dropdown menu, I want the other dropdown menu and textbox to be disabled before the user tries to submit. This is what I've done so far, but nothing seems to happen everytime I choose "None":
<form name="my_form" onsubmit="return submit()" action="/test" method="post">
<select id="month">
<option value="None">None</option>
<option value="0">January</option>
<option value="1">February</option>
<option value="2">March</option>
<option value="3">April</option>
<option value="4">May</option>
<option value="5">June</option>
<option value="6">July</option>
<option value="7">August</option>
<option value="8">September</option>
<option value="9">October</option>
<option value="10">November</option>
<option value="11">December</option>
</select>
<select id="day">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>
<input type="text" name="year" placeholder="Year" />
<input type="submit" value="Submit" />
</form>
<script>
function submit(){
var get_month_value = month.options[month.selectedIndex].text;
if(get_month_value == "None"){
document.getElementById("year").disabled = true;
document.getElementById("day").disabled = true;
return false;
}
else if(year == ""){
alert("Year must be filled out");
return false;
}
</script>
Where am I going wrong with this? Any help would be appreciated. Thanks.
Give form an ID and remove the onsubmit function:
<form id="my_form" name="my_form" action="/test" method="post">
Place the submit button outside the form and add the onclick function:
<input type="submit" value="Submit" onclick="submit();" />
Give year text field an ID:
<input type="text" id="year" name="year" placeholder="Year" />
Javascript:
function submit() {
var select = document.getElementById("month");
var get_month_value = select.options[select.selectedIndex].value;
var year = document.getElementById('year').value;
if ((get_month_value == "None") || (year == "")) {
alert("Please fill out the required fields");
} else {
document.getElementById("my_form").submit();
}
}
DEMO
HTML5 Date picker with "required" attribute(works):
<form id="dateForm" name="dateForm" action="/test" method="post">
Date: <input type="date" name="date" required />
<input type="submit" />
</form>
No need for JScript and html for dropdowns.
DEMO
Your code has the following errors:-
First of all you can't give your function the name submit in your form attribute.
You are missing } at the end of your function.
Your Input Text should have id=year not name.
Month is not defined.
year is not defined.
Change
these lines in your HTML:-
<form name="my_form" onsubmit="return validateForm()" action="/test" method="post">
<input type="text" id="year" placeholder="Year" />
Javascript:-
function validateForm(){
var month = document.getElementById('month');
var year = document.getElementById('year').value;
var get_month_value = month.options[month.selectedIndex].text;
if(get_month_value == "None"){
document.getElementById("year").disabled = true;
document.getElementById("day").disabled = true;
return false;
}
else if(year == ""){
alert("Year must be filled out");
return false;
}
}

Categories

Resources