HTML form failed to validate using the jQuery Validation Plugin - javascript

I'm aware that this is likely poorly formatted and/or coded. I'm looking for an answer as to why it doesn't give a message that the first name field is required. The submit button at the moment isn't working at all, no values are being printed to the screen. When just doing a form scrape it was working. Could anyone tell me why the validation for the one form isn't working? I made sure my jQuery validation plugin is hooked in. Bits of my html and JS code are below. This is for a school project.
<form id = "form">
<div>
<label for = "firstName">First Name</label>
<input type = "text" id = "firstName" placeholder = "Type First Name Here"
name = "firstName" required autofocus >
<br><br>
<label for = "lastName">Last Name</label>
<input type = "text" id = "lastName" name = "lastName">
</div>
<br>
<div>
<label for = "phone">Phone Number</label>
<input type = "tel" id = "phone">
</div>
<br>
<div> <p>
<label>Email</label>
<input type = "email" id = "email">
Password
<input type = "password" id = "pass">
</p>
</div>
<br>
<div> Which level of skill do you believe fits you (or your child) best?
</div>
Beginner<input type = "radio" value = "Beginner" name = "level">
Intermediate<input type = "radio" value = "Intermediate" name = "level">
Advanced<input type = "radio" value = "Advanced" name = "level">
<div id = "level"></div>
<br>
<br>
<label for = "age-spinner">Student Age</label>
<input id = "age-spinner" value = "5">
<br>
<br>
<div>Which days are you most available for a weekly piano lesson?</div>
<input type = "checkbox" value = "Monday" id = "monday" name = "days">Monday
<input type = "checkbox" value = "Tuesday" id = "tuesday" name =
"days">Tuesday
<input type = "checkbox" value = "Wednesday" id = "wednesday" name =
"days">Wednesday
<input type = "checkbox" value = "Thursday" id = "thursday" name =
"days">Thursday
<input type = "checkbox" value = "Friday" id = "friday" name = "days">Friday
<input type = "checkbox" value = "Saturday" id = "saturday" name =
"days">Saturday
<br>
<br>
<div>Best starting date? </div>
<input type = "text" id = "startDate">
</form>
<br><br>
<input type = "submit" id = "submit">
<button type= "button" id = "reset">Reset</button>
^^HTML Code. JS Code below. These are held in separate files.
$( "input[type='submit']" ).button();
$.validator.setDefaults({
submitHandler: function(){
var firstName = $("#firstName").val();
var lastName =$("#lastName").val();
var phone = $("#phone").val();
var email = $("#email").val();
var pass = $("#pass").val();
var age = $("#age-spinner").val();
var level = $("input[name='level']:checked").val();
var startDate = $("#startDate").datepicker({ dateFormat: 'dd,MM,yyyy' }).val();
var days = " ";
//function to fill in data inputted from days
$("input[name='days']:checked").each(function(){
days += $(this).val() + ", "
});
$("#output").append("<br><br>Name: " + firstName + " " + lastName)
.append("<br>Phone #: " + phone)
.append("<br>Email: " + email)
.append("<br>Password: " + pass)
.append("<br>Student Age: " + age)
.append("<br>Student Level: " + level)
.append("<br>Proposed Start Date: " + startDate)
.append("<br>Available Days: " + days);
alert("Passed validation and submitted.");
}//end submitHandler
});
$("#form").validate();

Related

How to go about using form validation with using just javascript and DOM elements?

Was given a puzzle to figure out which is to use just form validation using only js and the peculiar thing here is that there is no form name, and the types dont use IDs but they do have names, but the main objective besides that is to make sure at least there is some data entered on each input type (ie. fullname can even be 1 letter, as long as its one character). Another thing to note is I cannot change the html code in anyway. Since I cannot use form name in my validation, the examples I have seen online are helpful but not enough to the point where I can proceed. Any help will be appreciated.
<form action = "form.html" method = "get"><br/>
Name:<input type = "text" name = "fullname" value="Enter Full Name"/><br/>
Gender:<br/>
Male<input type = "radio" name = "gender" value="male"/>Female<input type = "radio" name = "gender"
value="female"/><br/>
Hobbies<br/>
Baseball <input type = "checkbox" name = "hobbies[]" value = "baseball" />
Football <input type = "checkbox" name = "hobbies[]" value = "football" />
Hockey <input type = "checkbox" name = "hobbies[]" value = "hockey" /><br/>
Favorite Show <select name = "show">
<option value = "">Choose Below</option>
<option value = "ATHF">Aqua Teen Hunger Force</option>
<option value = "Family Guy">Family Guy</option>
<option value = "Simpsons">Simpsons</option>
</select><br/>
Comments<br/>
<textarea cols = "50" rows = "6" name = "comments">Enter Comments</textarea><br/>
<input type = "submit" name = "submit" value = "enter me" />
</form>
Its a bit messy but its working . I dont change any HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
</style>
</head>
<body>
<form action = "form.html" method = "get"><br/>
Name:<input type = "text" name = "fullname" value="Enter Full Name"/><br/>
Gender:<br/>
Male<input type = "radio" name = "gender" value="male"/>Female<input type = "radio" name = "gender"
value="female"/><br/>
Hobbies<br/>
Baseball <input type = "checkbox" name = "hobbies[]" value = "baseball" />
Football <input type = "checkbox" name = "hobbies[]" value = "football" />
Hockey <input type = "checkbox" name = "hobbies[]" value = "hockey" /><br/>
Favorite Show <select name = "show">
<option value = "">Choose Below</option>
<option value = "ATHF">Aqua Teen Hunger Force</option>
<option value = "Family Guy">Family Guy</option>
<option value = "Simpsons">Simpsons</option>
</select><br/>
Comments<br/>
<textarea cols = "50" rows = "6" name = "comments">Enter Comments</textarea><br/>
<input type = "submit" name = "submit" value = "enter me" />
</form>
</body>
<script type="text/javascript">
function validate(){
name = document.getElementsByName("fullname")[0].value.length
gender1 = document.getElementsByName("gender")[0].checked
gender2 = document.getElementsByName("gender")[1].checked
hobbies1 = document.getElementsByName("hobbies[]")[0].checked
hobbies2 = document.getElementsByName("hobbies[]")[1].checked
hobbies3 = document.getElementsByName("hobbies[]")[2].checked
show = document.getElementsByName("show")[0].value
comment = document.getElementsByName("comments")[0].value.length
if(name==0 || (!gender1 && !gender2) || (!hobbies1 && !hobbies2 && !hobbies3) || comment==0 || show==""){
alert("please fill all")
}
}
button = document.getElementsByName("submit")
eButton = button[0].addEventListener("click",validate)
</script>
</html>

How to fix "TypeError: X is null"

I'm making a little site/server where i can send my name/last name/age etc to a php file.
my problem is that My JS won't pick up my input from the HTML and then change the PHP.
The exact error is: TypeError: firstName is null in Firefox
Tried it on different browser but i got the same result (as expected).
Also tried to switch the input ID's to names but that didn't work aswell.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="Lucas" content="Nothing important">
<title>Ajax form_1</title>
</head>
<body>
<h2>Form_2</h2>
<form>
<input type = "text" name = "firstName" placeholder = "voornaam">
<input type = "text" name = "lastName" placeholder = "achternaam">
<input type = "text" name = "age" placeholder = "leeftijd">
<input type = "text" name = "email" placeholder = "email">
<input type = "button" id = "submitButton" value = "submit">
</form>
<div id = "responseHere">Response comes here</div>
<script src="script.js"></script>
</body>
</html>
let firstName = document.getElementById("firstName");
let lastName = document.getElementById("lastName");
let age = document.getElementById("age");
let email = document.getElementById("email");
let submitButton = document.getElementById("submitButton");
let responseHere = document.getElementById("responseHere");
submitButton.addEventListener('click', ajax);
function ajax(){
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
responseHere.innerHTML = this.responseText;
}
};
let httpString = "form_1.php?firstName=" + firstName.value + "&lastName=" + lastName.value + "&age=" + age.value + "&email=" + email.value;
console.log(httpString);
xmlhttp.open("GET", httpString, true);
xmlhttp.send();
}
<?php
$firstName = $_GET['firstName'];
$lastName = $_GET['lastName']
$age = $_GET['age'];
$email = $_GET['email']
echo "<h2>Response Demo Form</h2><h3>";
echo "You submitted the following information<br><ul>";
echo "<li>Name: <strong> $firstName $lastName</strong></li>";
echo "<li>Age: $age</li>";
echo "<li>Age: $email</li>";
echo "</li></ul></h3>";
?>
You need to add a unique id attribute in html code
<form>
<input type = "text" id='firstName' name = "firstName" placeholder = "voornaam">
<input type = "text" id='lastName' name = "lastName" placeholder = "achternaam">
<input type = "text" id='age' name = "age" placeholder = "leeftijd">
<input type = "text" id='email' name = "email" placeholder = "email">
<input type = "button" id = "submitButton" value = "submit">
</form>

JS code for autocomplete while box checked

We need to enable auto-complete on this form. Whenever the checkbox is checked, the code should automatically copy the values from Shipping Name and Shipping Zip into the Billing Name and Billing Zip. If the checkbox is unchecked, the Billing Name and Billing Zip should go blank.
HTML Code
<pre>
<form>
<fieldset>
<legend>Shipping Information</legend>
<label for ="shippingName">Name:</label>
<input type = "text" name = "shipName" id = "shippingName" required><br/>
<label for = "shippingZip">Zip code:</label>
<input type = "text" name = "shipZip" id = "shippingZip" pattern = "[0-9]{5}" required><br/>
</fieldset>
<input type="checkbox" id="same" name="same" onchange= "billingFunction()"/>
<label for = "same">Is the Billing Information the Same?</label>
<fieldset>
<legend>Billing Information</legend>
<label for ="billingName">Name:</label>
<input type = "text" name = "billName" id = "billingName" required><br/>
<label for = "billingZip">Zip code:</label>
<input type = "text" name = "billZip" id = "billingZip" pattern = "[0-9]{5}" required><br/>
</fieldset>
<input type = "submit" value = "Verify"/>
</form>
</pre>
JS Code
<pre>
function billingFunction(){
var bn, bz, sn, sz;
if (document.getElementById('same').checked){
bn = document.getElementById('billingName').text;
sn = document.getElementById('shippingName').text;
bz = document.getElementById('billingZip').text;
sz = document.getElementById('shippingZip').text;
bn = sn;
bz = sz;
}
}
</pre>
This should work:
function billingFunction(){
var bn, bz, sn, sz;
bn = document.getElementById('billingName');
bz = document.getElementById('billingZip');
if (document.getElementById('same').checked){
sn = document.getElementById('shippingName').value;
sz = document.getElementById('shippingZip').value;
bn.value = sn;
bz.value = sz;
} else {
bn.value = '';
bz.value = '';
}
}
If you can use jquery you can simplify the function like this.
$('#same').change(function(){
var name, zip;
if ($('#same').prop('checked')){
name = $('#shippingName').val();
zip = $('#shippingZip').val();
}
$('#billingName').val(name);
$('#billingZip').val(zip);
});

Creating Id using javascript

I want to create staffid from three different textboxes values by getting their first letter & adding auto increment number atlast.
eg "staffname", "gender", "designation" result staffid: sgd01 & I want to auto display in the staff id textbox while staffid textbox is disabled. Here is the code below:
<input name="staffname" id="staffname" size="30" type="text" value placeholder=" Staff Name" onkeyup="quick()" class="formTxtInput">
Script
function quick() {
var gender = document.getElementById('gender').value;
var staffname = document.getElementById('staffname');
var desg = document.getElementById('desg').value;
var gen = gender.charAt(0);
var sn = staffname.charAt(0);
var dg = desg.charAt(0);
var val = gen + sn + dg;
document.getElementById('staffid').value = val;
}
You have a missing .value for var staffname. It should be
var staffname = document.getElementById('staffname').value;
Also your function needs to be called on every keyup on each of the 3 input boxes so that updated values can be processed
Here is a working sample: http://jsbin.com/vobikejejo/1/
Hope this helps :)
You can try by updating your function as below:
<script>
var num=01;
function quick() {
num+=1;
var gender = document.getElementById('gender').value;
var staffname = document.getElementById('staffname').value;
var desg = document.getElementById('desg').value;
var gen = gender.charAt(0);
var sn = staffname.charAt(0);
var dg = desg.charAt(0);
var val = gen + sn + dg + num;
document.getElementById('staffid').value = val;
}
By default there is no value, so it is not working. Try by setting the default value.
<input name="staffname" id="staffname" size="30" type="text" value="staffname" placeholder=" Staff Name" onkeyup="quick()" class="formTxtInput">
<input name="gender" id="gender" size="30" type="text" value="gender" placeholder=" Staff Name" class="formTxtInput">
<input name="desg" id="desg" size="30" type="text" value="desg" placeholder=" Staff Name"class="formTxtInput">
<input name="staffid" id="staffid" size="30" disabled="disabled" type="text" value placeholder=" Staff Name" class="formTxtInput">
YOu can view demo here 1

I need to display a message containing variables (answers from form) after form submit

I need to display the answer from the form in a story. The story must be displayed below the form only after the form is successfully submitted (not an alert), and with the form remaining on the page (not a new page). I am able to insert the form values into the story, but need help with displaying the story after form is submitted. I cannot use anything but html and javascript. I think this can be done with innerHTML.
<head><title>Questions</title>
<script type = "text/javascript" src="quiz1.js">
</script>
</head><body>
<h1>Tell Me About Yourself</h1>
<form name = "the_form" action = "" method = "post"
onSubmit = "var the_result = checkMandatory(); return the_result;">
Full Name:<input type = "text" name = "name" id = "name" /><br/>
Favourite Animal:<input type = "text" name = "animal" id = "animal"><br/>
Favourite Food:<input type = "text" name = "favFood" id = "favFood"><br/>
Favourite Destination:<input type = "text" name = "destination" id = "desitnation"><br/>
Least Favourite Food:<input type = "text" name = "leastFav" id = "leastFav"><br/>
Happiest Moment:<input type = "text" name = "moment" id = "moment"><br/>
Adjective that describes you:<input type = "text" name = "adjective" id = "adjective"><br/>
<br>
<input type="button" value="Submit" onClick = "checkMandatory(); return false;"/><br />
<br />
</form>
<div id="storyDiv"></div>
</body>
</html>
function checkMandatory()
{
// check the text field
// make a var for each question to access easier eg "favMeal"
var name = window.document.the_form.name.value;
//! means 'not'... flips around the if
if (!(name.indexOf(" ") > 0))
{
alert("You must give your full name.");
//return false stops the program
return false;
} else {
//firstName checks all character from 0 to whenever (space) occurs and strips it
var firstName = name.substring(0,name.indexOf(" "));
var name = window.document.the_form.name.value;
var animal = window.document.the_form.animal.value;
var favFood = window.document.the_form.favFood.value;
var destination = window.document.the_form.destination.value;
var leastFav = window.document.the_form.leastFav.value;
var moment = window.document.the_form.moment.value;
var adjective = window.document.the_form.adjective.value;
//alert("first name is " + firstName);
//use alert firstName to test the firstName function
document.write("The young person's name was "+firstName+". "+firstName+" loved to ride
"+animal+
" almost every day. "+firstName+"'s second happiest moment, only next to "+moment+", was in
"+destination+", where "+favFood+
" was served for breakfast, lunch and dinner. It was only when "+firstName+" was told that
"+favFood+
" is actually made from "+animal+", that it instantly became "+firstName+"'s least
favourite food, even worse than "+leastFav+
", and that made "+firstName+" feel very "+adjective+" indeed.")
//document.getElementById('storyDiv').innerHTML = document.getElementById('name').value;
//document.getElementById(‘storyDiv’).innerHTML="The boy's name was "+firstName;
//document.write(‘storyDiv’).innerHTML="The boy's name was " + firstName;
}
}
You can achieve this by posting your form using ajax.
Don't call writethetext(); in your submit button
I'll use jQuery in my solution:
$(function() {
$("form").on("submit", function(e) {
var data = JSON.stringify($("form").serializeArray());
e.preventDefault();
$.post("yourserver/path/", data, function(result) {
writethetext(result);
});
});
});
function checkMandatory() {
// check the text field
// make a var for each question to access easier eg "favMeal"
var name = window.document.the_form.name.value;
//! means 'not'... flips around the if
if (!(name.indexOf(" ") > 0)) {
alert("You must give your full name.");
//return false stops the program
return false;
} else {
//firstName checks all character from 0 to whenever (space) occurs and strips it
var firstName = name.substring(0, name.indexOf(" "));
//alert("first name is " + firstName);
//use alert firstName to test the firstName function
}
}
function writethetext() {
document.getElementById(‘storyDiv’).innerHTML =
("There once was a boy named" + name;)
var firstName = name.substring(0, name.indexOf(" "));
var name = window.document.the_form.name.value;
var animal = window.document.the_form.animal.value;
var favFood = window.document.the_form.favFood.value;
var destination = window.document.the_form.destination.value;
var leastFav = window.document.the_form.leastFav.value;
var moment = window.document.the_form.moment.value;
var adjective = window.document.the_form.adjective.value;
}
function writethetext(text) {
document.getElementById(‘storyDiv’).innerHTML = text;
}
}
<html>
<head>
<title>Questions</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="quiz1.js">
</script>
</head>
<body>
<h1>Tell Me About Yourself</h1>
<form name="the_form" action="" method="post" onSubmit="var the_result = checkMandatory(); return the_result;">
Full Name:
<input type="text" name="name" id="name" />
<br/>Favourite Animal:
<input type="text" name="animal" id="animal">
<br/>Favourite Food:
<input type="text" name="favFood" id="favFood">
<br/>Favourite Destination:
<input type="text" name="destination" id="desitnation">
<br/>Least Favourite Food:
<input type="text" name="leastFav" id="leastFav">
<br/>Happiest Moment:
<input type="text" name="moment" id="moment">
<br/>Adjective that describes you:
<input type="text" name="adjective" id="adjective">
<br/>
<br>
<input type="button" value="Submit" onClick="checkMandatory();
return false;" />
<br />
<br />
</form>
<div id="storyDiv"></div>
</body>
</html>

Categories

Resources