I am making a health questionnaire, I am having a few problems with it. The main problem is the else section. Can someone tell me why it isn't working and help me sort it?
The code I have is:
Assignment 4
Health Questionnaire
<body>
<form name="form1">
Please enter the following details: <p>
First Name: <br>
<input type="text" name="txtFirstName"> size="20" maxlength="20"> <p>
Surname: <br>
<input type="text" name="txtSurName"> size="30" maxlength="20"> <p>
Age: <br>
<input type="text" name="txtAge" size="3" maxlength="3"> <p>
Address Line 1: <br>
<input type="text" name="txtAddressline1" size="30" maxlength="30"> <p>
Address Line 2: <br>
<input type="text" name="txtAddressline2" size="30" maxlength="30"> <p>
City: <br>
<input type="text" name="txtCity" size="20" maxlength="20"> <p>
County: <br>
<input type="text" name="txtCounty" size="20" maxlength="20"> <p>
Post Code: <br>
<input type="text" name="txtPostCode" size="10" maxlength="10"> <p>
<input type="submit" value="Check Details" name=validateForm
onclick="validateForm_onclick()">
<script type ="text/javascript">
function validateForm_onclick()
{
var myForm = document.form1;
if(myForm.txtAge.value === "" || myForm.txtFirstName.value === ""||
myForm.txtSurName.value === ""|| myForm.txtAddressline1.value === ""||
myForm.txtAddressline2.value === ""|| myForm.txtCity.value === ""||
myForm.txtCounty.value === ""|| myForm.txtPostCode.value === "")
{
alert("Please complete all of the form");
if(myForm.txtFirstName.value ==="")
{
myForm.txtFirstName.focus();
}
else
{
myForm.txtSurName.focus();
}
else
{
myForm.txtFirstName.focus();
}
else
{
myForm.txtAge.focus();
}
else
{
myForm.txtAddressline1.focus();
}
else
{
myForm.txtAddressline2.focus();
}
else
{
myForm.txtCity.focus();
}
else
{
myForm.txtCounty.focus();
}
else
{
myForm.txtPostCode.focus();
}
}
else
{
alert("Thanks for completing the form " + myForm.txtName.value);
myForm.submit();
}
}
</script
</form>
</body>
I need to also keep the sizes on the names but need to hide that from the user.
Can someone give me some advice on how to change this?
Your form does not have a submit button.
Your code:
<input type="button" value="Check Details" name=validateForm
onclick="validateForm_onclick()">
Rectified code:
<input type="submit" value="Check Details" name=validateForm
onclick="validateForm_onclick()">
Also, the long list of else is illegal in JavaScript.
form name=form1 needs to have quotes: form name="form1"
And in case you don't want to use submit but stick to a button, insert this in your javascript:
else
{
alert("Thanks for completing the form " + myForm.txtName.value);
myForm.submit();
}
Related
I need to insert a regular expression to verify the input for URL and email is valid, so where would this go in the code to make it work without messing with anything else? I need to know exactly where it would go and how it would look.
window.onload = function() {
document.getElementById('ifBusiness').style.display = 'none';
}
function BusinessorResidence() {
var is_business = document.getElementById('businessCheck').checked;
if (is_business) {
document.getElementById('ifBusiness').style.display = 'block';
document.getElementById('ifResidence').style.display = 'none';
} else {
document.getElementById('ifBusiness').style.display = 'none';
document.getElementById('ifResidence').style.display = 'block';
}
}
function validateForm() {
var is_business = document.getElementById('businessCheck').checked;
var address = document.forms["myForm"]["address"];
var bname = document.forms["myForm"]["bname"];
var url = document.forms["myForm"]["url"];
var tax = document.forms["myForm"]["tax"];
var rname = document.forms["myForm"]["rname"];
var email = document.forms["myForm"]["email"];
// Address always has to be checked
if (address.value == "") {
alert("Please enter an address.");
address.focus();
return false;
}
// Check the bname, tax and url if a business is selected
if (is_business) {
if (bname.value == "") {
alert("Please enter a business name.");
// focus() is a method, not a property, so you need to call this function to actually focus the text input.
bname.focus();
return false;
}
if (tax.value == "") {
alert("Please enter a business tax ID.");
tax.focus();
return false;
}
if (url.value == "") {
alert("Please enter a business URL.");
url.focus();
return false;
}
}
// Else check the rname and the email
else {
if (rname.value == "") {
alert("Please enter a residence name.");
rname.focus();
return false;
}
if (email.value == "") {
alert("Please enter an email address.");
email.focus();
return false;
}
}
// Open the popup window.
// _blank refers to it being a new window
// SELU is the name we'll use for the window.
// The last string is the options we need.
var popup = window.open('', 'SELU', 'toolbar=0,scrollbars=0,location=0,statusb ar=0,menubar=0,resizable=0,width=400,height=400,left=312,top=234');
// Set the form target to the name of the newly created popup.
var form = document.querySelector('form[name="myForm"]');
form.setAttribute('target', 'SELU');
return true;
}
head {
text-align: center;
}
body {
text-align: center;
}
.bold {
font-weight: bold;
}
<!DOCTYPE html>
<html>
<head>
<title>Javascript Assignment</title>
<!-- the titles should be inside the title, not inside the <head> tag -->
<h1>Fill the form below</h1>
<!-- center tag is deprecated and should be replaced by CSS -->
</head>
<body>
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<p>
<b>Address: </b>
<input type="text" name="address">
</p>
<div>
<div>
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="businessCheck">This is a Business
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="residenceChceck">This is a Residence
<br>
<div id="ifBusiness" style="display:none">
<!-- <b> tag is deprecated. should be done with CSS -->
<span class="bold">Business Name:</span>
<input type="text" id="name" name="bname">
<br>
<span class="bold">Business Website URL:</span>
<input type="text" id="url" name="url">
<br>
<span class="bold">Business Tax ID: </span>
<input type="text" id="tax" name="tax">
</div>
<div id="ifResidence" style="display:none">
<b>Name: </b>
<input type="text" id="name" name="rname">
<br>
<b>Email: </b>
<input type="text" id="email" name="email">
</div>
</div>
</div>
<input type="submit" value="Submit">
</form>
<hr>
<hr>
</body>
</html>
To validate whether or not a user is inputting an url/email, simply change your input type to "url" or "email" and it will be validated for you.
Like so:
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<p>
<b>Address: </b>
<input type="text" name="address">
</p>
<div>
<div>
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="businessCheck">This is a Business
<input type="radio" onclick="javascript:BusinessorResidence();" name="businessresidence" id="residenceChceck">This is a Residence
<br>
<div id="ifBusiness" style="display:none">
<!-- <b> tag is deprecated. should be done with CSS -->
<span class="bold">Business Name:</span>
<input type="text" id="name" name="bname">
<br>
<span class="bold">Business Website URL:</span>
<input type="url" id="url" name="url">
<br>
<span class="bold">Business Tax ID: </span>
<input type="text" id="tax" name="tax">
</div>
<div id="ifResidence" style="display:none">
<b>Name: </b>
<input type="text" id="name" name="rname">
<br>
<b>Email: </b>
<input type="email" id="email" name="email">
</div>
</div>
</div>
<input type="submit" value="Submit">
</form>
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 == " ") {
my jquery is not connecting and I cannot figure out why. I've been stumped on this for hours and I cannot figure it out.
this is my html code. The file name is exercise6.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Exercise 6</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="JS/exercise6.js"> </script>
</head>
<body>
<form id="email_form" name="email_form" action="exercise6.html" method="get">
<fieldset class="info">
<legend>Contact Information</legend>
<p>
<input type="text" name="Lname" id="name2" value="" required />
<label for="name2"> Last</label>
</p>
<p>
<input type="text" name="mailAddie" id="mail1" value="" required />
<label for="mail1"> Address</label>
</p>
<p>
<input type="text" name="City" id="city1" value="" />
<label for="city1"> City</label>
</p>
<p>
<input type="text" name="State" id="state1" value="" />
<label for="state1"> State</label>
</p>
<p>
<input type="number" name="Zip" id="zip1" value="" />
<label for="zip1"> Zip</label>
</p>
<p>
<input type="number" name="phoneNum" id="number" />
<label for="number"> Phone</label>
</p>
</fieldset>
<fieldset>
<legend>Sign up for our email list</legend>
<p>
<label for="email_address1"> Email Address</label>
<input type="text" name="email_address1" id="email_address1" value="" />
<span>*</span><br>
</p>
<p>
<label for="email_address2"> Confirm Email Address</label>
<input type="text" name="email_address2" id="email_address2" value="" />
<span>*</span><br>
</p>
<p>
<label for="first_name"> First</label>
<input type="text" name="first_name" id="first_name" value="" />
<span>*</span><br>
</p>
</fieldset>
<p>
<label> </label>
<input type="submit" value="Join Our List" id="join_list" >
</p>
</form>
</body>
</html>
and this is my javascript. The file name is exercise6.js and it is located in a file named JS. I do not know what I am doing wrong.
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
)};
)};
Can anyone help me?
The last two lines of exercise6.js both have a syntax error.
Change:
)};
)};
To:
});
});
To find this yourself next time, try using web development IDE like NetBeans with the help of right click with mouse to inspect in browser debug console, which would have even shown you where is this kind of error.
Your js code has some errors for close the function "});" try this
$(document).ready(function() {
$("#join_list").click(function() {
var emailAddress1 = $("#email_address1").val();
var emailAddress2 = $("#email_address2").val();
var isValid = true;
if (emailAddress1 == "") {
$("#email_address1").next().text("This field is required.");
isValid = false;
} else {
$("#email_address1").next().text("");
}
if (emailAddress2 == "") {
$("#email_address2").next().text("This field is required.");
isValid = false;
} else {
$("#email_address2").next().text("");
}
if ($("#first_name").val() == "") {
$("#first_name").next().text("This field is required.");
isValid = false
} else {
$("#first_name").next().text("");
}
if (isValid) {
$("#email_form").submit();
}
});
});
I have this assignment in my class where we are to make a simple form with three required fields (out of five). I am having problems with getting my code to work.
This is via my professor...with what he wants
{
On submitting the form, the browser should check that :
Values for the required fields have been entered
Use regular expressions to check that the form of the entered input is proper for the email, telephone, and website fields. The forms to check for are:
Email: [alphanumeric string including . and _ ]# [alphanumeric string including . and _ ]. [alpha string]
Telephone: Either (ddd)ddd-dddd or ddd-ddd-dddd etc
Website: www.[alphanumeric string including . _ -].[com or net etc]
If any error is found, the form should not be submitted and appropriate error messages should be generated.
}
All validation must be "client side" i.e. on the browser using Javascript (not on any server and no Jquery or any programming other than Javascript and the required HTML). Use of any authoring tools is strictly and expressly forbidden.
This what I have now. Please help. Below is the code. What am I doing wrong?
<script language = "JavaScript">
<!--
function validateForm(){
//This is to check that required fields are filled
var x = document.contact.Name.value;
var y = document.contact.Email.value;
var z = document.contact.Website.value;
var p = document.contact.Phone.value;
if(x==null || x ==""){
alert('Name must be filled out');
return false;
}
if (y ==null || y == ""){
alert('Email must be filled out');
return false;
}
if (z == null || z == ""){
alert('Website must be filled out');
return false;
}
if(!isEmail()){
alert('This is not a correct Email format');
}
if (!isTelephone()){
var errorText = document.createTextNode(
"This is not a correct Phone number format");
}
if(!isWeb()){
errorText = document.createTextNode(
"This is not the correct Website format");
}
}
function isTelephone(){
//This checks that the phone number is in the required format
return document.contact.Phone.value.match(
/^\(\d\d\d-d\d\d\-\d\d\d\d$/);
}
function isEmail(){
//This is for checking email format
return document.contact.Email.value.match(
/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/);
}
function isWeb(){
return document.contact.Website.value.match(
/^([wW]{3}\.)?[a-zA-Z0-9\-.]{3,}\[a-zA-Z]{2,}(\.[a-zA-Z]{2,})?$/);
}
-->
</script>
<body>
<form name="contact" action="" method="post" onSubmit = "return validateForm();">
Name: <input type="textbox" name="Name" value="" > <font color = red>*Required </font><br>
Company: <input type="textbox" name="Company" value="" > <font color = red>Optional </font><br>
Email: <input type="textbox" name="Email" value="" > <font color = red>*Required </font><br>
Telephone: <input type="textbox" name="Telephone" value="" > <font color = red>Optional </font><br>
Website: <input type="textbox" name="Website" value="" ><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details">
<input type="reset" value="Clear"
ONCLICK="
alert('This will clear the form.');
Name.value=' '
Company.value=' '
Email.value=' '
Telephone.value=' '
Website.value=' '"><br>
</form>
</body>
</html>
Try this out:- https://jsfiddle.net/vduwxjmv/
This can be done without JavaScript also using required attribute at each html control for which value is mandatory. And for clear you can use input type as reset.
HTML:-
<form name="contact" action="" method="post">
Name: <input type="textbox" name="Name" value="" required> <font color = red>*Required </font><br>
Company: <input type="textbox" name="Company" value=""> <font color = red>Optional </font><br>
Email: <input type="textbox" name="Email" value="" required> <font color = red>*Required </font><br>
Telephone: <input type="textbox" name="Telephone" value="" > <font color = red>Optional </font><br>
Website: <input type="textbox" name="Website" value="" required><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details">
<input type="reset" value="Clear" />
You can do a check by using the following JavaScript code
var result = $("#form")[0].checkValidity();
or you may change input button
<input type="submit" value="Submit Contact Details">
<!DOCTYPE html>
<html>
<body>
<form name="contact" method="post">
Name: <input type="text" class="form-control" name="Name" placeholder="Name" required="required" /> <font color = red>*Required </font><br>
Company: <input type="text" class="form-control" name="Company" placeholder="Company" /> <font color = red>Optional </font><br>
Email: <input type="email" class="form-control" name="Email" placeholder="Email" required="required" /> <font color = red>*Required </font><br>
Telephone: <input type="text" class="form-control" name="Telephone" placeholder="Telephone"/> <font color = red>Optional </font><br>
Website: <input type="text" class="form-control" name="Website" placeholder="Website" required="required" /><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details">
<input type="reset" value="Clear"><br>
</form>
</body>
</html>
change the type from button to submit.
on giving the type as reset ,it will clear the contents.
on giving required="required", that field will be considered as a mandatory one.
<html>
<head>
<script language = "JavaScript">
function validateForm(thisVar){ alert('method Called From: ');alert(thisVar.value);alert(thisVar.name);
//This is to check that required fields are filled
var x = document.contact.Name.value;
var y = document.contact.Email.value;
var z = document.contact.Website.value;
var p = document.contact.Phone.value;
if(x==null || x ==""){
alert('Name must be filled out');
return false;
}
if (y ==null || y == ""){
alert('Email must be filled out');
return false;
}
if (z == null || z == ""){
alert('Website must be filled out');
return false;
}
if(!isEmail()){
alert('This is not a correct Email format');
}
if (!isTelephone()){
var errorText = document.createTextNode(
"This is not a correct Phone number format");
}
if(!isWeb()){
errorText = document.createTextNode(
"This is not the correct Website format");
}
}
function isTelephone(){
//This checks that the phone number is in the required format
return document.contact.Phone.value.match(
/^\(\d\d\d-d\d\d\-\d\d\d\d$/);
}
function isEmail(){
//This is for checking email format
return document.contact.Email.value.match(
/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/);
}
function isWeb(){
return document.contact.Website.value.match(
/^([wW]{3}\.)?[a-zA-Z0-9\-.]{3,}\[a-zA-Z]{2,}(\.[a-zA-Z]{2,})?$/);
}
</script>
</head>
<body>
<form name="contactForm" action="" method="post" onSubmit = "return validateForm(this);">
Name: <input type="textbox" name="Name" value="" > <font color = red>*Required </font><br>
Company: <input type="textbox" name="Company" value="" > <font color = red>Optional </font><br>
Email: <input type="textbox" name="Email" value="" > <font color = red>*Required </font><br>
Telephone: <input type="textbox" name="Telephone" value="" > <font color = red>Optional </font><br>
Website: <input type="textbox" name="Website" value="" ><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details" onclick="validateForm(this);">
<input type="reset" value="Clear"
ONCLICK="
alert('This will clear the form.');
Name.value=' '
Company.value=' '
Email.value=' '
Telephone.value=' '
Website.value=' '"><br>
</form>
</body>
</html>
You can validate it by two ways ---
use Submit type button
call validationForm on button click
Like --
<input type="submit" value="Submit Contact Details">
or
<input type="button" onclick="return validationForm();" value="Submit Contact Details">
you can check method call from to times 1st from onclick 2nd from onsubmit
Dont forget to appreciate (vote up).
for a uni assignment I need to validate my form before posting it. When an error occurs, there needs to be a text message in the same block as the error-input field (so no pop-up message). I'm not very good at JavaScript so I could really use some help.
Here's my html
<div id="form">
<form name="myForm" method="post" >
<p class="head">Deelnemer</p>
<fieldset id="deelnemer">
<label class="title">Naam:</label>
<input type="text" id="txtName" name="txtName" size="15"/>
</fieldset>
<p class="head">Opmerkingen</p>
<fieldset id="opmerkingen">
<textarea name="opmerkingen" rows="5" cols="40"></textarea>
</fieldset>
<p id="button">
<input type="submit" name="submit" value="Aanmelden" onclick="validate()"/>
</p>
</form>
And my Javascript so far (this show a popup message)
function validate()
{
var userName = document.getElementById("txtName").value;
if (userName.length == 0)
{
alert("Please, enter your name");
return false;
}
else
{
alert("Thank you, " + userName);
}
}
I hope someone has an answer for me! Thanks
So, what you want is just to make appear a message close to the textfield with the error?
For that, you jusst need to modify a little bit your htm and js:
<p class="head">Deelnemer</p>
<fieldset id="deelnemer">
<label class="title">Naam:</label>
<input type="text" id="txtName" name="txtName" size="15"/>
<div id="txtNameError" style="display: none;">Please, enter your name</div>
<p class="head">Opmerkingen</p>
<fieldset id="opmerkingen">
<textarea name="opmerkingen" rows="5" cols="40">
</textarea>
</fieldset>
<p id="button">
<input type="submit" name="submit" value="Aanmelden" onclick="validate()"/>
</p>
</form>
And, in your js file, you replace your alert by the id you need to dispay:
{
var userName = document.getElementById("txtName").value;
if (userName.length == 0)
{
/*alert("Please, enter your name");*/
document.getElementById("txtNameError").style.display = "block";
return false;
}
else
{
alert("Thank you, " + userName);
}
}