Getting Uncaught ReferenceError - javascript

I keep on getting this error Uncaught ReferenceError: calculatePrice is not defined at HTMLInputElement.onclick.
I have already seen the other answers on here regarding this error and none of them worked. I tried defining the script in body or head, didn't make a difference. I also think the function and button I connect it to are correct as I compared to a solution, so I really don't know why it is not working when I press it.
<html>
<head>
<link href="style/myStyles.css" type="text/css" rel="stylesheet">
<title> The Printing Company </title>
</head>
<body>
<script type="text/javascript"></script>
<script>
function calculatePrice() {
var quantity, type, price
quantity = document.getElementById("qty").value;
type = document.getElementById("cardstype").value;
if (type.includes("Basic"){
price = 10*(quantity/100);
} else if (type.includes("Medium"){
price = 15*(quantity/100);
} else if (type.includes("High"){
price = 20*(quantity/100);
}
alert("Your order will cost " + price + " GBP.");
}
</script>
<form action="form.php" method="post">
<label >Company Name</label><br>
<input name="name" type="text" required /><br>
<br>
<label>Contact email</label><br>
<input name="email" type="email" required /><br>
<br>
<label>Business Card type</label><br>
<select name="cardstype" id="cardstype">
<option value="" disabled selected>-Select Card Quality-</option>
<option value="Basic Quality">Basic Quality</option>
<option value="Medium Quality">Medium Quality</option>
<option value="High Quality">High Quality</option>
</select><br>
<br>
<label>Business Cards quantity</label><br>
<input name="qty" id ="qty" type="number" required Onchange = '
if( !( this.value >= 100 && this.value <= 1000 ) ) {
//alert the user that they have made a mistake
alert( this.value + " is not a valid quantity. Minimun quantity per order: 100 and maximum: 1000.");
this.value=""; //clears the text box
}'><br>
<br>
<input type="button" name="Price" value="Calculate Price" onclick="calculatePrice()"/>
<input type="submit" value="Submit Order"/>
</form>
</html>
Can anyone help?

I think You are missing the closing parentheses in your if statements:
if (type.includes("Basic") {
^^^ here
Working example:
function calculatePrice() {
var quantity, type, price;
quantity = document.getElementById("qty").value;
type = document.getElementById("cardstype").value;
if (type.includes("Basic")) {
price = 10*(quantity/100);
} else if (type.includes("Medium")) {
price = 15*(quantity/100);
} else if (type.includes("High")) {
price = 20*(quantity/100);
}
alert("Your order will cost " + price + " GBP.");
}
<form action="form.php" method="post">
<label >Company Name</label><br>
<input name="name" type="text" required /><br>
<br>
<label>Contact email</label><br>
<input name="email" type="email" required /><br>
<br>
<label>Business Card type</label><br>
<select name="cardstype" id="cardstype">
<option value="" disabled selected>-Select Card Quality-</option>
<option value="Basic Quality">Basic Quality</option>
<option value="Medium Quality">Medium Quality</option>
<option value="High Quality">High Quality</option>
</select><br>
<br>
<label>Business Cards quantity</label><br>
<input name="qty" id ="qty" type="number" required Onchange = '
if( !( this.value >= 100 && this.value <= 1000 ) ) {
//alert the user that they have made a mistake
alert( this.value + " is not a valid quantity. Minimun quantity per order: 100 and maximum: 1000.");
this.value=""; //clears the text box
}'><br>
<br>
<input type="button" name="Price" value="Calculate Price" onclick="calculatePrice(event)"/>
<input type="submit" value="Submit Order"/>
</form>

You have a few typos in your function:
Missing closing curly brace (looks fixed now)
Missing semicolon after variable definition: var quantity, type, price;
Mismatched parentheses in if/elseif conditions (3 times): if (type.includes("Basic")) {
The below code has these problems fixed:
<script>
function calculatePrice() {
var quantity, type, price;
quantity = document.getElementById("qty").value;
type = document.getElementById("cardstype").value;
if (type.includes("Basic")){
price = 10*(quantity/100);
} else if (type.includes("Medium")){
price = 15*(quantity/100);
} else if (type.includes("High")){
price = 20*(quantity/100);
}
alert("Your order will cost " + price + " GBP.");
}
</script>
Therefore, the function calculatePrice isn't defined and can't be called.

Related

Why doesn't Javascript validate my html code?

This is my first attempt at working with javascript and forms; for some reason my html website elements aren't being validated and I am not sure why. My goal with this form is trying to validate the elements that have an '*' next to them. For some reason the only element that is being validated is email and nothing else. Name, dates, the checkbox aren't. I have been trying to find a fix, but nothing seems to work.
<!doctype html>
<html>
<head>
<link href="styles.css" rel="stylesheet">
<script src="script.js"></script>
<meta charset="utf-8">
<title>Form</title>
</head>
<body>
<div class="container">
<h1>Travel Reservation Form</h1>
<h4>* denotes mandotory field</h4>
<form name="myForm" action="action_page.php" onsubmit="return validateForm()" method="post">
<fieldset>
<legend>Personal Details</legend>
<label class="align">Full name:<span>*</span></label> <input type="text" name="fullname" placeholder="James Bond">
<br><br>
<label class="align">Email<span>*</span></label>
<input type="email" name="mail" placeholder="james#gmail.com">
<br><br>
<label class="align">Date of Birth<span>*</span></label> <input type="date" name="DOB" placeholder="dd/mm/yy">
</fieldset>
<br>
<label>Select Tour Package<span>*</span>:</label>
<select name="package">
<option value="1">Tokyo</option>
<option value="2">Shanghai</option>
<option value="3">Bangkok</option>
<option value="4">Jakarta</option>
<option value="5">Mumbai</option>
</select>
<label>Number of persons<span>*</span>:</label>
<select name="party">
<option value="1">One Adult</option>
<option value="2">Two Adults</option>
<option value="3">Three Adults</option>
<option value="4">Four Adults</option>
<option value="5">Five Adults</option>
</select>
<br><br>
<label>Arrival Date<span>*</span>:</label> <input type="date" name="arrival" placeholder="dd/mm/yy">
<br><br>
<p>What Intrests you the most?<span>*</span>:</p>
<input class="alignp" type="checkbox" name="interest" value="shopping"> Shopping <br><br>
<input class="alignp" type="checkbox" name="interest" value="dining"> Dining <br><br>
<input class="alignp" type="checkbox" name="interest" value="dancing"> Dancing <br><br>
<input class="alignp" type="checkbox" name="interest" value="SightS"> Sightseeing <br><br><br>
<label>Discount Coupon code:</label> <input type="text" name="dis_code" value=""><br><br>
<label>Terms and Conditions<span>*</span><input type="radio" name="tos" value="yes" checked>I agree</label>
<input type="radio" name="tos" value="yes">I disagree
<p>Please provide any additional information below:- </p>
<textarea name="message" rows="5" cols="45" placeholder="Please type here...."></textarea><br><br>
<button class="btn-submit" type="submit" value="Submit">Submit</button>
<button class="btn-reset" type="reset" value="Reset">Reset</button>
</form>
</div>
</body>
</html>
Here is the javascript that is being linked in the html. I am unsure whether the issue is with my html code or with my javascript.
// JavaScript Document
function validateForm()
{
var name = document.forms["myForm"]["name"].value;
var email = document.forms["myForm"]["email"].value;
var dob = document.forms["myForm"]["DOB"].value;
var packages = document.forms["myForm"]["package"].value;
var arrival = document.forms["myForm"]["arrival"].value;
//var interest = document.forms["form"]["interest"].value;
var ToS = document.forms["myForm"]["tos"].value;
var checkbox = document.querySelector('input[name="interest"]:checked');
var matches = name.match(/\d+/g);
if (matches != null) {
alert("Name has a number in it!");
}
if (name == "") {
alert("Name must be filled out");
return false;
}
if (email == "") {
alert("Email must be filled out");
return false;
}
if (dob == "") {
alert("Date of Birth must not be empty");
return false;
}
if (arrival == "") {
alert("Arrival Date must not be empty");
return false;
}
if(ToS == false) {
alert("You must agree to the Terms of Service");
return false;
}
if(validateEmail(email) == false){
alert("Must enter a valid email");
}
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
if(dob != '' && !dob.match(re)) {
alert("Invalid date format");
return false;
}
if(arrival != '' && !arrival.match(re)) {
alert("Invalid arrival date format") ;
return false;
}
if(name.length >= 30){
alert("Name must be less than 30 characters!");
return false;
}
if(!checkbox){
alert("Please select an interest!");
return false;
}
}
function validateEmail(email)
{
return /\S+#\S+\.\S+/.test(email);
}
So I have no idea what your PHP form did, so I actually just pulled all the form code for now. There were a lot of little issues but honest mistakes. Example: you don't want a return statement after every validation if you want to continue validating the rest of the fields. I combined some separate validations into if/else's since they were validations on the same field. I used ID's to make my life easier and since I dumped the form code. Feel free to swap back to what you want. I also updated your regex since the date field returns YYYY/MM/DD. Since this doesn't post anywhere you can play with it for a while, before tying back into your php form. I also pulled the check for 30 characters and added a max field length to name. You could also set min and max date ranges for the date fields and a bunch of other things to help make the fields themselves more foolproof. There are also libraries that handle this kind of thing for you, you don't have to re-invent the wheel, but if you're just looking to play around with it this should get you started. Good Luck
<!doctype html>
<html>
<body>
<div class="container">
<h1>Travel Reservation Form</h1>
<h4>* denotes mandotory field</h4>
<fieldset>
<legend>Personal Details</legend>
<label class="align">Full name:<span>*</span></label> <input type="text" name="fullname" id='name' maxlength="30" placeholder="James Bond">
<br><br>
<label class="align">Email<span>*</span></label>
<input id="email" type="email" name="mail" placeholder="james#gmail.com">
<br><br>
<label class="align">Date of Birth<span>*</span></label> <input type="date" id="dob" name="DOB" placeholder="dd/mm/yy">
</fieldset>
<br>
<label>Select Tour Package<span>*</span>:</label>
<select id='package' name="package">
<option value="1">Tokyo</option>
<option value="2">Shanghai</option>
<option value="3">Bangkok</option>
<option value="4">Jakarta</option>
<option value="5">Mumbai</option>
</select>
<label>Number of persons<span>*</span>:</label>
<select name="party">
<option value="1">One Adult</option>
<option value="2">Two Adults</option>
<option value="3">Three Adults</option>
<option value="4">Four Adults</option>
<option value="5">Five Adults</option>
</select>
<br><br>
<label>Arrival Date<span>*</span>:</label> <input type="date" name="arrival" id="arrival" placeholder="dd/mm/yy">
<br><br>
<p>What Intrests you the most?<span>*</span>:</p>
<input class="alignp" type="checkbox" name="interest" value="shopping"> Shopping <br><br>
<input class="alignp" type="checkbox" name="interest" value="dining"> Dining <br><br>
<input class="alignp" type="checkbox" name="interest" value="dancing"> Dancing <br><br>
<input class="alignp" type="checkbox" name="interest" value="SightS"> Sightseeing <br><br><br>
<label>Discount Coupon code:</label> <input type="text" name="dis_code" value=""><br><br>
<label>Terms and Conditions<span>*</span>
<input type="radio" name="tos" id="accpeted" value="agree" checked>I agree</label>
<input type="radio" name="tos" id="unaccepted" value="disagree">I disagree
<p>Please provide any additional information below:- </p>
<textarea name="message" rows="5" cols="45" placeholder="Please type here...."></textarea><br><br>
<button class="btn-submit" id="submit" onclick="return validateForm()">Submit</button>
</div>
<script>
// JavaScript Document
function validateForm() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var dob = document.getElementById("dob").value;
//Select Box
var e = document.getElementById("package");
// Selected Item
var packages = e.options[e.selectedIndex].value;
var arrival = document.getElementById("arrival").value;
//var interest = document.getElementById("").value;
var tos = document.querySelector('input[name="tos"]:checked').value;
//var checkbox = document.getElementById("").value;;
var matches = name.match(/\d+/g);
var re = /^\d{4}([.\/-])\d{2}\1\d{2}$/;
if (!name) {
alert("Name must be filled out");
} else {
if (matches != null) {
alert("Name has a number in it!: " + name);
}
}
if (!email) {
alert("Email must be filled out");
} else {
if (validateEmail(email) == false) {
alert("Must enter a valid email: " + email);
}
}
if (!dob) {
alert("Date of Birth must not be empty");
} else {
if (!dob.match(re)) {
alert(" Dob has Invalid date format: " + dob);
}
}
if (!arrival) {
alert("Arrival Date must not be empty");
} else {
if (!arrival.match(re)) {
alert(" Dob has Invalid date format: " + arrival);
}
}
if (tos != "agree") {
alert("You must agree to the Terms of Service");
}
}
function validateEmail(email) {
return /\S+#\S+\.\S+/.test(email);
}
</script>
</body>
</html>

Javascript Comparing String Not Working

I need to do comparing string because I need to have calculation. The string from select option in HTML and another will be the variable string.
This is my HTML Code:
<label>Freight Cost Mode</label>
<select class="form-control" id="freightcostmode_insert" name="freightCostMode_insert" onchange="val()">
<option>Percentage</option>
<option>Monetary</option>
</select>
<input class="form-control" id="freightcost_insert" type="text" placeholder="Freight Cost Mode" name="freightCost_insert" onkeyup="val()">
<input type="text" class="form-control" id="freight">
This is my javascript code:
<script>
function val() {
var input = document.getElementById("freightcostmode_insert").value;
var calculation = document.getElementById("freightCost_insert").value;
if(inputing == "Percentage"){
document.getElementById('freight').value = calculation*1.5;
}if else(inputing == 'Monetary'){
}
}
</script>
For first your inputing variable does not exist - maybe input.
For second parse the calculation value into a number.
Also you have some syntax errors in your code.
function val() {
var input = document.getElementById("freightcostmode_insert").value;
var calculation = document.getElementById("freightcost_insert").value;
if(input == "Percentage"){
document.getElementById('freight').value = parseInt(calculation) * 1.5;
} else if(input == 'Monetary'){
}
}
<label>Freight Cost Mode</label>
<select class="form-control" id="freightcostmode_insert" name="freightCostMode_insert" onchange="val()">
<option>Percentage</option>
<option>Monetary</option>
</select>
<input class="form-control" id="freightcost_insert" type="text" placeholder="Freight Cost Mode" name="freightCost_insert" onkeyup="val()">
<input type="text" class="form-control" id="freight">
Working Code
function val() {
var input = document.getElementById("freightcostmode_insert").value,
calculation = document.getElementById("freightcost_insert").value
document.getElementById('freight').value = input === "Percentage" ?
calculation * 1.5 : calculation * 2.5;
}
<label>Freight Cost Mode</label>
<select class="form-control" id="freightcostmode_insert" name="freightCostMode_insert" onchange="val()">
<option>Percentage</option>
<option>Monetary</option>
</select>
<input class="form-control" id="freightcost_insert" type="text" placeholder="Freight Cost Mode" name="freightCost_insert" onkeyup="val()">
<input type="text" class="form-control" id="freight">

JSON Javascript & HTML

I am a grade 11 level computer programmer and encountered some difficulties when trying to complete our JSON assignment. The goal is to save an object to local storage, but my html and js do not do so. Instead, nothing happens at all. All feedback is appreciated.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" language="javascript" src="JDOS.js">
</script>
<title>Announcements Storage</title>
</head>
<body>
<form>
<fieldset>
<legend>Add New Announcement</legend>
Title:<br>
<input required id="title" type="text"><br>
Category:<br>
<input required id="category" type ="text"><br>
Creator:<br>
<input required id="creator" type="text"><br>
Type:
<select required id='type' name="type" >
<option value="Event">Event</option>
<option value="Reminder">Reminder</option>
<option value="General">General</option>
</select><br>
Date and Time:<br>
<input required id="date" type="date"><br>
<input required id="time" type="time"><br>
Sex:<br>
<select required id='sex'>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="All">All</option>
</select><br>
Grade:<br>
<input required id='grade' type='text'><br>
Message:<br>
<textarea required id="message" rows="10" cols="50">Type
announcement here</textarea><br>
<input type="submit" onclick="createAnnouncement()" value="Post">
</fieldset>
</form>
<div id="showAnnouncement"></div>
</body>
</html>
Javascript begins here:
function createAnnouncement() {
var title= document.getElementById('title').value;
var category= document.getElementById('category').value;
var creator= document.getElementById('creator').value;
var type= document.getElementById('type').value;
var datetime= document.getElementById('datetime').value;
var sex= document.getElementById('sex').value;
var grade= document.getElementById('grade').value;
var message= document.getElementById('message').value;
var announcement = {
Title: title,
Category: category,
Creator: creator,
Type: type,
DateTime: datetime,
Sex: sex,
Grade: grade,
Message: message
};
var x = JSON.stringify(announcement);
localStorage.setItem('announcement', x);
}
function showAnnouncement(){
var obj = localStorage.getItem('announcement').value;
var obj2 = JSON.parse (obj);
document.getElementById('showAnnouncement').innerHTML = "title:" + obj2.title
+ "category:" + obj2.category + "creator:" + obj2.creator + "type:" +
obj2.type + "datetime:" + obj2.datetime + "sex:" + obj2.sex + "grade:" +
obj2.grade + "message:" + obj2.message;
}
You have some errors on your logic here.
Since your input is created as type="submit", it will try to do a HTTP POST instead of calling your createAnnouncement() function. You can change it to type="button".
After that, you need to find a way to trigger the showAnnouncement() function, this could be an element such as an <a> or another <button>.

How to multiple (a*b) two input text value and show it Dynamicly with text change in javascript?

i want to show the money that customer must pay and my inputs are like this :
<input type="text" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" class="form-control" placeholder="quantity" id="txt" name="limit">
when the input text is changing i want to show the total cost (quantity*cost) in a <p> tag Dynamicly how can it be with javascript?
You can try this:
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" onchange="calculate()">
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" onchange="calculate()">
<p id="result"></p>
And javascript part:
function calculate() {
var cost = Number(document.getElementById("credit"));
var limit = Number(document.getElementById("limit"));
document.getElementById("result").innerHTML= cost*limit;
}
You must ensure you entered numbers in inputs.
All of the above will generate errors if both the boxes are blank . Try this code , its tested and running .
<script>
function calc()
{
var credit = document.getElementById("credit").value;
var limit = document.getElementById("limit").value;
if(credit == '' && limit != '')
{
document.getElementById("cost").innerHTML = parseInt(limit);
}
else if(limit == '' && credit != '')
{
document.getElementById("cost").innerHTML = parseInt(credit);
}
else if(limit!= '' && credit!= '')
{
document.getElementById("cost").innerHTML = parseInt(limit) * parseInt(credit);
}
else
{
document.getElementById("cost").innerHTML = '';
}
}
</script>
</head>
<input type="number" value="0" min="0" class="form-control" placeholder="cost" id="credit" name="credit" onkeyup="calc();">
<input type="number" value="0" min="0" class="form-control" placeholder="quantity" id="limit" name="limit" onkeyup="calc();">
<p id="cost"></p>
Hope this will be useful
// get cost field
var _cost = document.getElementById("cost");
_cost.addEventListener('keyup',function(event){
updateCost()
})
// get quantity field
var _quantity = document.getElementById("quantity");
_quantity.addEventListener('keyup',function(event){
updateCost()
})
function updateCost(){
var _getCost = document.getElementById("cost").value;
var _getQuantity = document.getElementById("quantity").value;
var _total = _getCost*_getQuantity;
console.log(_total);
document.getElementById("updateValue").textContent = ""; // Erase previous value
document.getElementById("updateValue").textContent = _total // update with new value
}
jsfiddle
In case you consider using JQuery I've made this fiddle.
See if it works for you.
https://fiddle.jshell.net/9cpbdegt/
$(document).ready(function() {
$('#credit').keyup(function() {
recalc();
});
$('#limit').keyup(function() {
recalc();
});
function recalc() {
var credit = $("#credit").val();
var limit = $("#limit").val();
var result = credit * limit;
$("#result").text(result);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" value="0">x
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" value="0">
<p id="result">0</p>
Try this:
<script >
function myFunction() {
document.getElementById('totalcost').innerHTML = document.getElementById('txt').value * document.getElementById('txt2').value;}
</script>
Also, change your HTML to this:
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="quantity" id="txt2" name="limit">
Enter cost and quantity.
Note the change with the second input: id='txt' was changed to id='txt2'. This is because no 2 elements can have the same id.
Note: Untested.

Basic JavaScript validation not working

I'm trying to make a simple form with JavaScript validation. It has four fields: title, email address, rating and comments. As far as I know, the code I have here should work to validate the form and I should not be allowed to submit it but whenever I press the submit button none of the prompts appear and the browser submits the form. Could someone let me know where I am going wrong please? I'd imagine there is a simple solution or something I am forgetting but I'm pretty new to this so apologies if it's something very obvious.
The HTML and JavaScript code is:
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var e=document.forms["review"]["Title"].value;
var s=document.forms["review"]["Email"].value;
var t=document.forms["review"]["Rating"].value;
var c=document.forms["review"]["Comments"].value;
var atsym=s.indexOf("#");
var dotsym=s.lastindexOf(".");
if (e==null || e=="")
{
document.getElementById("valAlert").innerHTML="Please Enter a Title";
return false;
}
else if (s==null || s=="" || atsym<1 || dotsym<atsym+2 || dotsym+2>=s.length)
{
document.getElementById("valAlert").innerHTML="That is not a valid email address!";
return false;
}
else if (t=="0")
{
document.getElementById("valAlert").innerHTML="You must enter a rating";
return false;
}
else if (c==null || c=="")
{
document.getElementById("valAlert").innerHTML="You need to enter some kind of comment.";
return false;
}
else
{
alert ("Your review of " + t + "has been submitted!");
}
}
</script>
</head>
<body>
<div id="valAlert"></div>
<form name="review" onsubmit="return validateForm()">
<fieldset>
Enter Title:
<input type="text" name="Title">
</br>
</br>
Enter Email Address:
<input type="text" name="Email">
</br>
</br>
Please Enter Your Rating:
<select name="Rating">
<option value="0">(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
</br>
</br>
<textarea name="Comments" rows="8" colspan="40">Comments:</textarea>
</fieldset>
</br>
</br>
<fieldset>
<input class="button" type="submit" value="Submit"/>
</fieldset>
</form>
</body>
please make a null value check before doing the operations like below
var dotsym=s.lastindexOf(".");
Add the null check for variable 's'.Please check the function naming convention below
obj.lastindexOf(); TO obj.lastIndexOf(".");
You’ve said there were no errors, but you might just be missing them when the form submits and the console is cleared.
If you’re using Chrome/Chromium, you can enable breaking on exceptions in the Sources tab of the developer tools (the icon on the far right should be purple or blue):
In Firefox, it’s in the Debugger Options menu:
As #Rajesh says, the casing you have on lastindexOf is wrong; it should be lastIndexOf.
Now, let’s fix everything else up, starting with formatting:
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var e = document.forms["review"]["Title"].value;
var s = document.forms["review"]["Email"].value;
var t = document.forms["review"]["Rating"].value;
var c = document.forms["review"]["Comments"].value;
var atsym = s.indexOf("#");
var dotsym = s.lastIndexOf(".");
if (e == null || e == "")
{
document.getElementById("valAlert").innerHTML = "Please Enter a Title";
return false;
}
else if (s == null || s == "" || atsym < 1 || dotsym < atsym + 2 || dotsym + 2 >= s.length)
{
document.getElementById("valAlert").innerHTML = "That is not a valid email address!";
return false;
}
else if (t == "0")
{
document.getElementById("valAlert").innerHTML = "You must enter a rating";
return false;
}
else if (c == null || c == "")
{
document.getElementById("valAlert").innerHTML = "You need to enter some kind of comment.";
return false;
}
else
{
alert("Your review of " + t + " has been submitted!");
}
}
</script>
</head>
<body>
<div id="valAlert"></div>
<form name="review" onsubmit="return validateForm()">
<fieldset>
Enter Title:
<input type="text" name="Title" />
</br>
</br>
Enter Email Address:
<input type="text" name="Email" />
</br>
</br>
Please Enter Your Rating:
<select name="Rating">
<option value="0">(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
</br>
</br>
<textarea name="Comments" rows="8" colspan="40">Comments:</textarea>
</fieldset>
</br>
</br>
<fieldset>
<input class="button" type="submit" value="Submit" />
</fieldset>
</form>
</body>
You’re missing a DTD and a closing </html>, so add those:
<!DOCTYPE html>
<html>
…
</html>
Next, </br> doesn’t exist. It’s <br />.
<form name="review" onsubmit="return validateForm()">
<fieldset>
Enter Title:
<input type="text" name="Title" />
<br />
<br />
Enter Email Address:
<input type="text" name="Email" />
<br />
<br />
Please Enter Your Rating:
<select name="Rating">
<option value="0">(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
<br />
<br />
<textarea name="Comments" rows="8" colspan="40">Comments:</textarea>
</fieldset>
<br />
<br />
<fieldset>
<input class="button" type="submit" value="Submit" />
</fieldset>
</form>
Here:
var e = document.forms["review"]["Title"].value;
var s = document.forms["review"]["Email"].value;
var t = document.forms["review"]["Rating"].value;
var c = document.forms["review"]["Comments"].value;
the properties are valid JavaScript identifiers, so you can write them with the dot syntax:
var e = document.forms.review.Title.value;
var s = document.forms.review.Email.value;
var t = document.forms.review.Rating.value;
var c = document.forms.review.Comments.value;
You should probably give them clearer names, too; I think you used the wrong one in that last alert, and this will help:
var title = document.forms.review.Title.value;
var email = document.forms.review.Email.value;
var rating = document.forms.review.Rating.value;
var comments = document.forms.review.Comments.value;
Next, you don’t need elses when you’re returning from the if case no matter what, so you can drop those. The values of text inputs can never be null, so stop checking for those. It’ll also save some typing (or copying) to keep valAlert as a variable.
var atsym = email.indexOf("#");
var dotsym = email.lastindexOf(".");
var valAlert = document.getElementById("valAlert");
if (title === "") {
valAlert.innerHTML = "Please Enter a Title";
return false;
}
if (atsym < 1 || dotsym < atsym + 2 || dotsym + 2 >= s.length) {
valAlert.innerHTML = "That is not a valid email address!";
return false;
}
if (rating == "0") {
valAlert.innerHTML = "You must enter a rating";
return false;
}
if (comments == "") {
valAlert.innerHTML = "You need to enter some kind of comment.";
return false;
}
alert("Your review of " + title + " has been submitted!");
Voilà! But wait; there’s more. The best things in life web development don’t need JavaScript, and this is no exception.
<!DOCTYPE html>
<html>
<head>
<title>HTML5 validation</title>
</head>
<body>
<form>
<fieldset>
<label>
Enter title:
<input type="text" name="title" required />
</label>
<label>
Enter e-mail address:
<input type="email" name="email" required />
</label>
<label>
Please enter your rating:
<select name="rating" required>
<option>(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
</label>
<textarea name="comments" rows="8" cols="40" placeholder="Comments" required></textarea>
</fieldset>
<fieldset>
<button class="button">Submit</button>
</fieldset>
</form>
</body>
</html>
I beg to differ on your comments. You are getting console errors. Specially, it is erroring out whenever you try to run the parsers on s and s is empty. You need to move the logic into the if clause AFTER you have verified it has a value:
else if (s == null || s == "") {
document.getElementById("valAlert").innerHTML = "Please enter an email address";
return false;
}
else if (s.indexOf("#") < 1 || s.lastindexOf(".") < s.indexOf("#")+ 2 || s.lastindexOf(".")+ 2 >= s.length) {
document.getElementById("valAlert").innerHTML = "This is not a valid email address!";
return false;
}
Here is a Fiddle

Categories

Resources