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
Related
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>
so I've created a form. I'm trying to use JavaScript to validate fields. When I press submit, it does nothing. It just sends me to a page saying 'Your file was not found.' I do realize that the code is mostly HTML and not JS. I've been testing as I'm going and it's not working already. Any help is appreciated
Here is my code:
function validateForm() {
var firstname = document.myForm.fname.value;
if (firstname === "" || firstname === " ") {
alert("First name is empty!");
return false;
}
var middlename = document.myForm.middle.value;
if (middle == "" || middle == " ") {
alert("Middle name is empty");
return false;
}
}
function validateForm() {
var firstname = document.myForm.fname.value;
if (firstname === "" || firstname === " ") {
alert("First name is empty!");
return false;
}
var middlename = document.myForm.middle.value;
if (middle == "" || middle == " ") {
alert("Middle name is empty");
return false;
}
var lastname = document.myForm.lname.value;
if (lastname == "" || lastname == " ") {
alert("Last name is empty");
return false;
}
}
<!DOCTYPE html>
<html>
<head>
<title>My form validation</title>
</head>
<body>
<form name="myForm" action="fakeFormCheck.php" onsubmit="validateForm()" method="post">
<fieldset>
*First Name:
<input type="text" name="fname">
<br><br>
Middle/Initial:
<input type="text" name="middle">
<br><br>
*Last Name:
<input type="text" name="lname">
<br><br>
*Email:
<input type="text" name="email">
<br><br>
Phone:
<input type="number" name="number">
<br><br>
</fieldset>
<br>
<fieldset>
*Reason:
<select name="choice">
<option value="Information">Infor reques</option>
<option value="feedback">Feedback</option>
<option value="other">Other</option>
</select>
<br><br>
*Message: <br>
<textarea name="message" rows="7" cols="30">
</textarea>
</fieldset>
<input type="submit" value="Send">
<input type="reset" value="Clear">
</form>
</body>
</html>
Add preventDefault() to the validateForm function & return true once the form is valid
function validateForm(e) {
e.preventDefault();
var firstname = document.myForm.fname.value;
if (firstname === "" || firstname === " ") {
alert("First name is empty!");
return false;
}
var middlename = document.myForm.middle.value;
if (middlename == "" || middlename == " ") {
alert("Middle name is empty");
return false;
}
}
<form name="myForm" action="fakeFormCheck.php" onsubmit="validateForm(event)" method="post">
<fieldset>
*First Name:
<input type="text" name="fname">
<br><br> Middle/Initial:
<input type="text" name="middle">
<br><br> *Last Name:
<input type="text" name="lname">
<br><br> *Email:
<input type="text" name="email">
<br><br> Phone:
<input type="number" name="number">
<br><br>
</fieldset>
<br>
<fieldset>
*Reason:
<select name="choice">
<option value="Information">Infor reques</option>
<option value="feedback">Feedback</option>
<option value="other">Other</option>
</select>
<br><br> *Message: <br>
<textarea name="message" rows="7" cols="30">
</textarea>
</fieldset>
<input type="submit" value="Send">
<input type="reset" value="Clear">
</form>
Try attaching the handler in Javascript rather than inline-eval-HTML, and using preventDefault to prevent the default form submission.
<form name="myForm" action="fakeFormCheck.php" method="post">
and
document.querySelector('form[name="myForm"]').addEventListener('submit', (e) => {
// do tests
if (invalid) {
// something is invalid, prevent the default action of submitting the form:
e.preventDefault();
}
// else the form will submit by default
});
Use return in onsubmit="validateForm()" for example onsubmit="return validateForm()". second thing you are taking the middle name in middlename variable but your checking with some other varible if (middle == "" || middle == " ") {
I'm having problems trying to validate an entire form using Javascript.
"Add JavaScript code to produce an error message and suppress submission of the form if any quantity field contains non-numeric data. (It's OK for a quantity to be empty, but if it's non-empty, it must have only numbers.) Add an action= attribute to your tag to submit the form to a website (not going to put actual website). Test that the form is submitted correctly when the quantities are numeric or empty, and that an error message is produced otherwise."
I've done all the instructions asked me to do and it isn't working. We are supposed to use the form that we created in one of the previous labs. Here is the code that I have been working on.
<!DOCTYPE html>
<html>
<head>
<title>Lab 6, Part 3</title>
<meta charset="UTF-8"/>
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
<script type="text/javascript">
function validateForm(){
var a = document.forms["myform"]["Pokemon"].value;
var b = document.forms["myform"]["Pokeball"].value;
var c = document.forms["myform"]["Pikachu"].value;
var d = document.forms["myform"]["firstname"].value;
var e = document.forms["myform"]["lastname"].value;
var f = document.forms["myform"]["streetaddress"].value;
var g = document.forms["myform"]["city"].value;
var h = document.forms["myform"]["zipcode"].value;
if (a = null || a == ""){
alert("Grapes must be filled out!");
return false;
}
if (b = null || b == ""){
alert("Cherries must be filled out!");
return false;
}
if (c = null || c == ""){
alert("Strawberries must be filled out!");
return false;
}
if (d = null || d == ""){
alert("First Name must be filled out!");
return false;
}
if (e = null || e == ""){
alert("Last Name must be filled out!");
return false;
}
if (f = null || f == ""){
alert("Street Address must be filled out!");
return false;
}
if (g = null || g == ""){
alert("City must be filled out!");
return false;
}
if (h = null || h == ""){
alert("Zip Code must be filled out!");
return false;
}
}
</script>
</head>
<body><form>
<form name="myform" action="http://weblab.kennesaw.edu/formtest.php"
onsubmit="return validateForm()"
method = "post">
<h1 style="text-align:center">Lab 6, Part 3</h1>
<h2 style="text-align:center">IT 3203</h2>
<p style="text-align:center">Main Page!</p>
<p>Grapes</p><input type=text size=3 maxlength=3 name="Pokemon">
<p>Cherries</p><input type=text size=3 maxlength=3 name="Pokeball">
<p>Strawberries</p><input type=text size=3 maxlength=3 name="Pikachu">
<br>
<label>First Name
<input type="text"
name="firstname" id="firstname"
size="25" />
</label>
<br>
<br>
<label>Last Name
<input type="text"
name="lastname" id="lastname"
size="25" />
</label>
<br>
<br>
<label>Street Address
<input type="text"
name="streetaddress" id="streetaddress"
size="35" />
</label>
<br>
<br>
<label>City
<input type="text"
name="city" id="city"
size="25" />
</label>
<label>State:
<select name="state">
<option>Please Select</option>
<option>Alabama</option>
<option>Alaska</option>
<option>Arizona</option>
<option>Arkansas</option>
<option>California</option>
<option>Colorado</option>
<option>Connecticut</option>
<option>Delaware</option>
<option>Florida</option>
<option>Georgia</option>
<option>Hawaii</option>
<option>Idaho</option>
<option>Illinois</option>
<option>Indiana</option>
<option>Iowa</option>
<option>Kansas</option>
<option>Kentucky</option>
<option>Louisiana</option>
<option>Maine</option>
<option>Maryland</option>
<option>Massachusetts</option>
<option>Michigan</option>
<option>Minnesota</option>
<option>Mississippi</option>
<option>Missouri</option>
<option>Montana</option>
<option>Nebraska</option>
<option>Nevada</option>
<option>New Hampshire</option>
<option>New Jersey</option>
<option>New Mexico</option>
<option>New York</option>
<option>North Carolina</option>
<option>North Dakota</option>
<option>Ohio</option>
<option>Oklahoma</option>
<option>Oregon</option>
<option>Pennsylvania</option>
<option>Rhode Island</option>
<option>South Carolina</option>
<option>South Dakota</option>
<option>Tennessee</option>
<option>Texas</option>
<option>Utah</option>
<option>Vermont</option>
<option>Virginia</option>
<option>Washington</option>
<option>West Virginia</option>
<option>Wisconsin</option>
<option>Wyoming</option>
</select>
</label>
<br>
<br>
<label>Zip code:
<input type="text"
name="zipcode" id="zipcode"
size="20" />
</label>
</form>
<br>
<br>
<label>Visa
<input type="radio" name="pref_payment"
id="pref_payment_visa" value="visa" checked />
</label><br />
<label>MasterCard
<input type="radio" name="pref_payment"
id="pref_payment_master" value="master" checked />
</label><br />
<label>American Express
<input type="radio" name="pref_payment"
id="pref_payment_american" value="american" checked />
</label><br />
<input type="button" onclick="confirmation()" value="submit">
</form>
</body>
</html>
It is probably something minor that I have overlooked or something. Oh and we had to save the files in .php so maybe that has a lot to do with it.
1) Check your form tag. You got two there.
<form>
2) Your submit button type.
Should be:
type="submit"
Not:
type="button"
And no need to add:
onclick="confirmation()"
http://plnkr.co/edit/Ml2KWgfU5KG5gmBpf8Fe?p=preview
I am trying to get a form with multiple fields validate when the submit button is pressed.
If a field is invalid then a message appears next to the field. I can get one of the invalid messages to appear but not all of them. The function I am using is below.
function checkForm() {
document.getElementById("test").onsubmit=function(){
var title = document.getElementById("titles");
if (title.selectedIndex == -1) {
return null;
}
var email = document.getElementById('email');
//Regular Expression for checking email
var emailRegEx = /[-\w.]+#([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
document.getElementById("errEmail").style.display="inline";
return false;
}
if(document.getElementById("fname").value==""){
document.getElementById("errfName").style.display="inline";
return false;
}
else {
return true;
}
if(document.getElementById("lname").value==""){
document.getElementById("errlName").style.display="inline";
return false;
}
else {
return true;
}
}
}
html below
<form name ="reg" id="test">
<fieldset id="controls">
<div>
<label for="title">Title: </label>
<select id="titles">
<option value="mr" selected="selected">Title</option>
<option value="mr">Mr.</option>
<option value="mrs">Mrs.</option>
<option value="ms">Ms.</option>
<option value="miss">Miss</option>
</select>
</div>
<div>
<label for="fname">First Name: </label>
<input id="fname" type="text"><span id="errfName" class="error">* Please Enter a First Name</span>
</div>
<div>
<label for="lname">Last Name: </label>
<input id="lname" type="text"><span id="errlName" class="error">* Please Enter a Last Name</span>
</div>
<div>
<label for="email">Email: </label>
<input id="email" type="text" size="40"><span id="errEmail" class="error">* Please enter a valid email</span>
</div>
<div>
<input type="submit" value="submit">
</div>
</fieldset>
</form>
</body>
</html>
try this:
function checkForm() {
var errors = [];
document.getElementById("test").onsubmit=function(){
var title = document.getElementById("titles");
if (title.selectedIndex == -1) {
return null;
}
var email = document.getElementById('email');
//Regular Expression for checking email
var emailRegEx = /[-\w.]+#([A-z0-9][-A-z0-9]+\.)+[A-z]{2,4}/;
if (!emailRegEx.test(email.value)) {
errors.push("errEmail");
}
if(document.getElementById("fname").value==""){
errors.push("errfName");
}
if(document.getElementById("lname").value==""){
errors.push("errlName");
}
if(errors.length > 0 ){
for(var i=0;i<errors.length;i++){
document.getElementById(errors[i]).style.display="inline";
}
return false;
}else{
return true
}
}
}
I am trying to validate the form input but my validation is not working.
The string must have at least one letter or digit,
an integer should be between 0-11 and should pick at least one fruit.
But even if i dont enter any input,
it just go to the input_ok.html file.
It needs to pop-up the error window.
Here is my code:
function validateInput() {
var str = myForm.inputString.value;
var nbrStr = myForm.inputInteger.value;
var nbr = parseInt(nbrStr);
var fruit = myForm.fruit.value;
if (str != "" && nbrStr != "" && fruit != "" && !isNaN(nbr) && nbr < 11) {
return true;
} else {
var msg = "";
var strError = false;
if (str == "") {
msg += "\nPlease enter a string with at least one letter or digit";
strError = true;
}
if (nbrStr == "") {
msg += "\nPlease enter an integer in the range 0-11";
} else if (isNaN(nbr)) {
msg += "\nPlease enter an integer";
} else if (nbr > 11) {
msg += "\nPlease enter an integer less than 11";
}
if (strError) {
myForm.inputString.focus();
} else {
myForm.inputInteger.focus();
}
alert(msg);
}
return false;
}
<body>
<h1>Week 08, Exercise 01</h1>
<form action="week08_01servlet"
method="post"
name="myForm"
onsubmit="return validateInput();">
<p>Please enter the following information,
and then click the submit button.</p>
<p class="indent">A string with at least one letter or digit
<input type="text" name="inputString">
<br>An integer in the range 0-11
<input type="text" name="inputInteger">
<br>Pick a fruit <select name="fruit">
<option value="---">---
<option value="apple">apple
<option value="banana">banana
<option value="cherry">cherry
<option value="pear">pear
</select></p>
<p><input type="submit" value="Submit"></p>
<input type="hidden" name="command" value="do_it">
</form>
</body>
This is clearly homework, but I beleave every question deservers an answer. Valid xhtml5, javascript checked with jslint and compressed with ajaxmin. Enjoy.
Also, you might want to read ppks Introduction to Forms.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Week 08, Exercise 01</title>
<link rel="stylesheet" href="Week08_01.css">
<script>
function validateInput(c){var f=c.inputString.value,d=c.inputInteger.value,b=parseInt(d,10),g=c.fruit.value;if(f!==""&&d!==""&&g!==""&&!isNaN(b)&&b>=0&&b<11)return true;else{var a="",e=false;if(f===""){a+="\nPlease enter a string with at least one letter or digit";e=true}if(d==="")a+="\nPlease enter an integer in the range 0-11";else if(isNaN(b))a+="\nPlease enter an integer";else if(b<=0)a+="\nPlease enter a positive integer";else if(b>11)a+="\nPlease enter an integer less than 11";if(e)c.inputString.focus();else c.inputInteger.focus();alert(a);return false}}
</script>
</head>
<body>
<h1>Week 08, Exercise 01</h1>
<form action="week08_01servlet"
method="post"
name="myForm"
onsubmit="return validateInput(this);">
<p>Please enter the following information,
and then click the submit button.</p>
<p class="indent">A string with at least one letter or digit
<input type="text" name="inputString" />
<br>An integer in the range 0-11
<input type="text" name="inputInteger" />
<br />Pick a fruit <select name="fruit">
<option value="---">---</option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="cherry">cherry</option>
<option value="pear">pear</option>
</select></p>
<p><input type="submit" value="Submit">
<input type="hidden" name="command" value="do_it"></p>
</form>
</body>
</html>