Form Validation and Alert issues in JavaScript - javascript

The following is a complete copy of the project I'm working on. I'm having problems with the JavaScript validating segments of the form as well as JavaScript producing an alert at the end of the function.
The idea is to have the functions is to validate the form so that, if you are over 18: you only need the first and last name fields filled out. (The content doesn't really matter so long as it works.) On the other hand however, if you are under 18, the function will need to validate guardian details as well.
Until somewhat recent changes were made however this worked fine, the problem is I left the project for several weeks so I don't know what changes were made to be able to undo them. Ideally the basic code wouldn't change too much, I'm looking for a quick fix or stop-gap measures that will have the same effect.
<html>
<head>
<meta charset="utf-8">
<title>Work Field Trip Registration</title>
<script type="text/javascript">
function HideReveal() {
if (document.getElementById("YesNo").selectedIndex == "1") {
document.getElementById("ifYes").style.display = "block";
Required();
//alert('1st Option Tested');
}
else if (document.getElementById("YesNo").selectedIndex == "0") {
document.getElementById("ifYes").style.display = "none";
Required();
//alert('2nd Option Tested');
}
}
function Required() {
if (document.getElementById("YesNo").selectedIndex == "1") {
AddRequirement();
//alert("Step1");
}
else {
NoRequirement();
//alert("Step2");
}
}
function NoRequirement() {
document.getElementById("GuardName").removeAttribute("required");
document.getElementById("GuardPhone").removeAttribute("required");
//alert("Step3");
}
function AddRequirement() {
document.forms("death")("GuardianName").setAttribute("required", "");
document.forms("death")("GuardianNumber").setAttribute("required", "");
//alert("Step4");
}
function validateForm() {
var a = document.forms("death")("GuardianName").value;
var b = document.forms("death")("GuardianNumber").value;
var c = document.forms("death")("FirstName").value;
var d = document.forms("death")("LastName").value;
if (document.getElementById("YesNo").selectedIndex == "1")
{
if (a == "" || b == "") {
alert("Please fill ALL required fields");
}
else {
alert("Registration Complete!");
}
}
else if (c == "" || d == "") {
alert("Please fill ALL required fields")
}
else {
alert("Registration Complete!")
}
}
</script>
</head>
<body>
<h2>Work Field Trip Registration!</h2>
<h4>Please enter your details.</h4>
<form name="death">
First Name:<br>
<input required type="text" name="FirstName"><br>
Last Name:<br>
<input required type="text" name="LastName"><br>
Gender:<br>
<select name="dMenu">
<option>Male</option>
<option>Female</option>
</select><br><br>
Are you under 18?
<select id="YesNo" onChange="HideReveal()" name="dMenu">
<option name="OptionNo" id="OptionNo" value="0">No</option>
<option name="OptionYes" id="OptionYes" value="1">Yes</option>
</select><br><br>
<div id="ifYes" style="display:none">
Please enter your Parent/Guardian's name:<br>
<input type="text" id="GuardName" name="GuardianName"><br>
Please enter your Parent/Guardian's phone number:<br>
<input type="text" id="GuardPhone" name="GuardianNumber"><br>
</div>
<input onClick="validateForm()" type="submit" value="Submit">
</form>
</body>
</html>

1) you don't need to call validate if you already set field to required. The browser will handle that for you.
2. I wonder why you used 'getElementbyId' in NoRequirement() but document.forms in AddRequirement().
In anycase here is a modified version of your code. cheers
<html>
<head>
<meta charset="utf-8">
<title>Work Field Trip Registration</title>
<script type="text/javascript">
function HideReveal() {
if (document.getElementById("YesNo").selectedIndex == "1") {
document.getElementById("ifYes").style.display = "block";
Required();
//alert('1st Option Tested');
}
else if (document.getElementById("YesNo").selectedIndex == "0") {
document.getElementById("ifYes").style.display = "none";
Required();
//alert('2nd Option Tested');
}
}
function Required() {
if (document.getElementById("YesNo").selectedIndex == "1") {
AddRequirement();
//alert("Step1");
}
else {
NoRequirement();
//alert("Step2");
}
}
function NoRequirement() {
document.getElementById("GuardName").removeAttribute("required");
document.getElementById("GuardPhone").removeAttribute("required");
//alert("Step3");
}
function AddRequirement() {
document.getElementById('GuardName').setAttribute("required","")
document.getElementById('GuardPhone').setAttribute("required","")
//alert("Step4");
}
</script>
</head>
<body>
<h2>Work Field Trip Registration!</h2>
<h4>Please enter your details.</h4>
<form name="death">
First Name:<br>
<input required type="text" name="FirstName"><br>
Last Name:<br>
<input required type="text" name="LastName"><br>
Gender:<br>
<select name="dMenu">
<option>Male</option>
<option>Female</option>
</select><br><br>
Are you under 18?
<select id="YesNo" onChange="HideReveal()" name="dMenu">
<option name="OptionNo" id="OptionNo" value="0">No</option>
<option name="OptionYes" id="OptionYes" value="1">Yes</option>
</select><br><br>
<div id="ifYes" style="display:none">
Please enter your Parent/Guardian's name:<br>
<input type="text" id="GuardName" name="GuardianName"><br>
Please enter your Parent/Guardian's phone number:<br>
<input type="text" id="GuardPhone" name="GuardianNumber"><br>
</div>
<input type="submit" value="Submit">
</form>
</body>
</html>

Related

How To Fill-Up a particular field of HTML form Based On dropdown selection made

Any way of making this code work with a select dropdown instead of a button? I am trying to use this to fill in a address from a dropdown and allow the user to modify as needs are needed.
<HEAD>
<TITLE>Test</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function testResults (form) {
var TestVar1 = form.input[0].checked;
var TestVar2 = form.input[1].checked;
if (TestVar1 == true) {
form.textbox.value = "Full Home Automation Package";
} else if (TestVar2 == true){
form.textbox.value = "Some Other Package";
} else if (TestVar1 == false && TestVar2 == false) {
form.textbox.value = "";
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="POST">Choose a Service: <BR>
<INPUT TYPE="radio" NAME="input" VALUE="red" onChange="testResults(this.form)">Service 1<P>
<INPUT TYPE="radio" NAME="input" VALUE="blue" onChange="testResults(this.form)">Service 2<P>
<P>Service Package Selected:</P> <INPUT TYPE="text" ID="textbox" NAME="selected" VALUE=""></div><p>
</FORM>
</BODY>
thanks for any help
You can use onchange on select and then if the value matches change the text of the input.
<!DOCTYPE html>
<html>
<HEAD>
<TITLE>Test</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function testResults(value) {
let textbox = document.getElementById("textbox");
if (value === '') {
textbox.value === '';
} else if (value === 'service1') {
textbox.value = 'Full Home Automation Package';
} else if (value === 'service2') {
textbox.value = "Some Other Package";
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="myform" ACTION="" METHOD="POST">Choose a Service: <BR>
<select onchange="testResults(value)" name="service">
<option disabled selected>Choose one</option>
<option value="service1">service1</option>
<option value="service2">service2</option>
</select>
<P>Service Package Selected:</P> <INPUT TYPE="text" ID="textbox" NAME="selected" VALUE=""></div>
<p>
</FORM>
</BODY>
</html>

Submit Button Not working but if I remove its JavaScript it works

This is my index.html file. It has JavaScript but when JavaScript validation works >Submit button doesn't perform any action. But when I remove JavaScript code it submits the data to the database.
I need to understand where my code has faults or mistakes and why this is happening. How to validate that the arrival date should be smaller than the departure date.
<!DOCTYPE html>
<head>
<title>Book Accomodations</title>
<link rel="stylesheet" href="style.css">
<script>
function validate(){
var x =document.forms["myform"]["fname"].value;
var y =document.forms["myform"]["lname"].value;
var email =document.forms["myform"]["email"].value;
var filter = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
var getSelectedValue = document.querySelector( 'input[name="payment"]:checked');
if (x == "" || x == null) {
alert("First Name must be filled out");
return false;
} else if (y == "" || y == null) {
alert(" Last Name must be filled out");
return false;
}
else if (!email.match(filter)) {
alert(" Enter Proper Email ID");
return false;
}
else if(document.getElementById("country").value == "")
{
alert("Please select a country");
return false;
} else if(getSelectedValue == null) {
alert("Select Payment Mode")
return false;
}
return false;
}
</script>
</head>
<body>
<div class="form">
<form name ="myform" action="function.php" onsubmit="return validate();" id="form" method="POST" >
<label for="fname">First Name:</label>
<input type="text" id="fname" name="fname" /><br>
<label for="lname">Last Name:</label>
<input type="text" id="lname" name="lname" /><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" /><br>
<label for="arrival">Arrival Date:</label>
<input type="date" id="arrival " name="adate" ><br>
<label for="departure">Departure Date:</label>
<input type="date" id="departure " name="ddate" />
<br>
<label for="country">Choose a Country:</label>
<select id="country" name="country" form="myform" >
<option disabled selected value> -- select an option -- </option>
<option value="India">India</option>
<option value="U.S.A.">U.S.A.</option>
<option value="Nepal">Nepal</option>
<option value="Bangladesh">Bangladesh</option>
<option value="Germany">Germany</option>
<option value="Spain">Spain</option>
<option value="Italy">Italy</option>
<option value="Sri Lanka">Sri Lanka</option>
<option value="China">China</option>
</select>
<p>Payment Mode:</p>
<input type="radio" id="deb"
name="payment" value="Debit" />
<label for="deb">Debit Card</label>
<input type="radio" id="cred"
name="payment" value="Credit"/>
<label for="Credit">Credit Card</label>
<br>
<input type="submit" id="submit" name="submit" value="submit" style="width: 100px;"/>
<input type="reset" value="Reset" style="width: 100px; "/>
</form> </div>
</body>
You should return true at the end of your validate() function if your validation was successful. Right now you always return false. Thats why the button doesn´t seams to work.
Seems like you missed something.
You should return true after succesfull validation.
if (x == "" || x == null) {
alert("First Name must be filled out");
return false;
} else if (y == "" || y == null) {
alert("Last Name must be filled out");
return false;
} else if (!email.match(filter)) {
alert("Enter Proper Email ID");
return false;
} else if (document.getElementById("country").value == "") {
alert("Please select a country");
return false;
} else if (getSelectedValue == null) {
alert("Select Payment Mode")
return false;
} else {
return true;
}
Or just return true after if-else statement.

JQuery Form Submission not Storing Value?

I have a custom method for validating the user input, but my form doesn't seem to be submitting. Also, the URL changes after my first submission, and the jquery only runs once the URL's changed.
The purpose of this code is to check if the information submitted is in a database. The function runs, but the value for the name field doesn't seem to be stored upon submission, and so I keep getting the error for name.
Here's my code:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<title>Smiles Galore (SG)</title>
<script>
$(document).ready(function(){
$('#target').on('submit', function(){
var emailChecker = $('#email').val();
var idChecker = $('#number').val();
var passCheck = $('#pwd').val();
var userName = $('#text').val;
if (userName.length <2){
alert("Please enter a name");
}
else{
if (idChecker.toString().length != 8){
alert("That's not a proper input for ID. Please provide a proper ID");
}
else{
if (!hasUpperCase(passCheck)){
alert("That's not a password. Enter a proper password.");
}
else if(!/[0-9]/.test(passCheck)){
alert("That's not a password. Enter a proper password.");
}
else if(passCheck.length > 8){
alert("That's not a password. Enter a proper password.");
}
else{
Verification(userName,emailChecker,passCheck,idChecker);
}
}
}
function hasUpperCase(word){
return word.toLowerCase()!=word;
}
function Verification(userName1,emailCheck1,passChecker,idCheck){
var selection = $("list").val();
alert("Hello");
$.post('Access.php',{'Patron Email Address':emailCheck1,'Patron Name':userName1,'Patron ID':idCheck,'Patron Password':passChecker},function(data){
if (data=='0'){
alert("The email is incorrect");
return;
}
else{
alert("You good");
if (selection == "Search for Appointment"){
$.post('Process.php',{'Patron Email Address':emailCheck1},function(){});
}
else if (selection == "Schedule an Appointment"){
return;
}
else if (selection == "Cancel an Appointment"){
return;
}
else if (selection == "Create/Register an Account"){
return;
}
return;
}
});
}
return false;
});
});
</script>
</head>
<body>
<form id="target">
<div class="form-group">
<label for="text">Name:</label>
<input type="text" class="form-control" id="text">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="form-group">
<label for="number">ID:</label>
<input type="number" class="form-control" id="number">
</div><br>
<label for="list">Select an Option:</label><br>
<select name="Select an Option:" id="list">
<option value="Schedule an Appointment">Schedule an Appointment</option>
<option value="Cancel an Appointment">Cancel an Appointment</option>
<option value="Search for Appointment">Search for Appointment(s)</option>
<option value="Create/Register an Account">Create/Register an Account</option>
</select><br>
<br><div>
<input type="submit" class="btn btn-primary mb-2" value="Continue">
</div>
</form>
</body>
You don't have a () after val for name like you do on the other variables.
Change var userName = $('#text').val; to var userName = $('#text').val();
That will fix your name problem.
Also noticed that you don't have a # in your jquery selector for selection.
Change var selection = $("list").val(); to var selection = $("#list").val();

how to change display none to block when form submits

I am learning JSP, javascript and a little jquery in my own time so please don't mind the probably horrible code or logic but I am making a form and when I submit the form I want it to display 3 labels showing the inputs, as seen in the code below I have it working so far as submitting but I can't seem to figure out how to change the CSS display from none to block. It's probably staring at me in the face but I can't figure it out.
JSP
<html>
<body>
<link type="text/css" rel="stylesheet" href="<%=request.getContextPath()%>/dylan/css/styles.css" />
<form action="form.jsp" id="test" name="test" method="POST">
<label>Please enter your name:</label>
<input name="Name" id="Name">
<br>
<br>
<label>Please enter your number:</label>
<input name="Num" id="Num">
<br>
<br>
<label>Please select your location:</label>
<select name="Location" id="Location">
<option value=""></option>
<option value="USA">USA</option>
<option value="UK">UK</option>
<option value="Ireland">Ireland</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
</select>
<br>
<br>
<button type="button" id="btnsubmit" name="btnsubmit" onclick="myFunction()">Submit</button>
<br>
<p><label id="lblName" style="display:none;"><% out.println(request.getParameter("Name")); %></label></p>
<p><label id="lblNumber" style="display:none;"><% out.println(request.getParameter("Num")); %></label></p>
<p><label id="lblLocation" style="display:none;"><% out.println(request.getParameter("Location")); %></label></p>
<script type="text/javascript" src="<%=request.getContextPath()%>/dylan/js/form.js"></script>
</form>
</body>
</html>
In the label I am setting the all 3 of the styles to none, I have no idea how to change that to block when submitting the form.
css
body {
background-color:#066;
color:#fff;
}
form {
width:400px;
height:240px;
Background-color:#000;
margin-left:auto;
margin-right:auto;
margin-top:170px;
Padding:10px;
border-style:solid;
border-width:5px;
border-radius:25px;
text-align:center;
}
javascript
function myFunction() {
var mainname, mainnum, mainloc;
mainname = document.getElementById("Name").value;
mainnum = document.getElementById("Num").value;
mainloc = document.getElementById("Location").options[document.getElementById("Location").selectedIndex].value;
if (mainname == "") {
alert("Please enter your name");
return false;
}
if (mainnum == "") {
alert("Please enter your Number");
return false;
}
if (mainloc == '') {
alert("Please select a country from the list");
return false;
}
document.getElementById("test").submit();
}
You can set the display to block as below.
document.getElementById('lblName').style.display = 'block';
document.getElementById('lblNumber').style.display = 'block';
document.getElementById('lblLocation').style.display = 'block';
If you have many labels you could use:
var labels = document.getElementsByTagName('label');
for(var i=0; i<labels.length; i++){
labels[i].style.display = 'block';
}

Adding Span with Class to a input tag with Jquery

I am trying to add a Span after my Input that will have the class "error" and the text "test".
I've tried the append, and insertAfter methods. I can get the code to work on jsfiddle but I cannot get the code to work on my application.
I have put the HTML and JS/Jquery below. My end result would have a Span (with the class error) next to each input with the type text. I would then set a value for this span based on a validation loop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Zito - Lab 7</title>
<link rel="stylesheet" href="main.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="reservation.js" type="text/javascript"></script>
</head>
<body>
<h1>Reservation Request</h1>
<form action="response.html" method="get"
name="reservation_form" id="reservation_form">
<fieldset>
<legend>General Information</legend>
<label for="arrival_date">Arrival date:</label>
<input type="text" name="arrival_date" id="arrival_date" autofocus><br>
<label for="nights">Nights:</label>
<input type="text" name="nights" id="nights"><br>
<label>Adults:</label>
<select name="adults" id="adults">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
<label>Children:</label>
<select name="children" id="children">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select><br>
</fieldset>
<fieldset>
<legend>Preferences</legend>
<label>Room type:</label>
<input type="radio" name="room" id="standard" class="left" checked>Standard
<input type="radio" name="room" id="business" class="left">Business
<input type="radio" name="room" id="suite" class="left last">Suite<br>
<label>Bed type:</label>
<input type="radio" name="bed" id="king" class="left" checked>King
<input type="radio" name="bed" id="double" class="left last">Double Double<br>
<input type="checkbox" name="smoking" id="smoking">Smoking<br>
</fieldset>
<fieldset>
<legend>Contact Information</legend>
<label for="name">Name:</label>
<input type="text" name="name" id="name"><br>
<label for="email">Email:</label>
<input type="text" name="email" id="email"><br>
<label for="phone">Phone:</label>
<input type="text" name="phone" id="phone" placeholder="999-999-9999"><br>
</fieldset>
<input type="submit" id="submit" value="Submit Request"><br>
</form>
</body>
</html>
JS/JQuery
$(document).ready(function() {
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
var phonePattern = /\b(\d{3})([-])(\d{3})([-])(\d{4})\b/;
var datePattern = /\b(0[1-9]|1[012])([/])(0[1-9]|1[0-9]|2[0-9]|3[01])([/])((20)\d\d)\b/;
$(":text").after("<span class='error'>*</span>");
$("#arrival_date").focus();
$("#reservation_form").submit(
function(event) {
var isValid = true;
// validate arrival date
var arrivalDate = $("#arrival_date").val();
if (arrivalDate == "") {
$("#arrival_date").next().text("This field is required");
isValid = false;
} else if (!datePattern.test(arrivalDate)) {
$("#arrival_date").next().text("Must be in the format 12/12/2012");
isValid = false;
} else {
$("#arrival_date").next().text("");
}
// validate nights
var nights = $("#nights").val();
if (nights == "") {
$("#nights").next().text("This field is required");
isValid = false;
} else if ((isNaN(parseInt(nights))) || (parseInt(nights) <=0)) {
$("#nights").next().text("This field must be a number and not zero");
isValid = false;
} else {
$("#nights").next().text("");
}
// validate name
var name = $("#name").val();
if (name == "") {
$("#name").next().text("This field is required");
isValid = false;
} else {
$("#name").next().text("");
}
// validate email
var email = $("#email").val();
if (email == "") {
$("#email").next().text("This field is required");
isValid = false;
} else if (!emailPattern.test(email) ) {
$("#email").next().text("Must be a valid email address.");
isValid = false;
} else {
$("#email").next().text("");
}
// validate phone
var phone = $("#phone").val();
if (phone == "") {
$("#phone").next().text("This field is required");
isValid = false;
} else if (!phonePattern.test(phone) ) {
$("#phone").next().text("Must be in the format 999-999-9999");
isValid = false;
} else {
$("#phone").next().text("");
}
if (isValid == false) {
event.preventDefault();
$("#arrival_date").focus();
}
}
);
}); // end ready
Most easy way is to add a Div container around the form and just append the warning to that. To effectively append after an element you need to give it a class or id.
var email = $("#email"); //using class instead of input:text
var html = "<span class='error'>TEST!</span>"
email.after( html );
But I personally would like something like this better:
var generateError = function(){
var html = "<div id='error' style='top: 0; left:0; width:100%; height: 50px; background-color: red; text-allign: center; display:none; z-index: 100;'> ERROR!!</div>"
$(body).append( html );
}
var showError = function( text ){
var err = $("#error");
err.html( text );
err.show(500).delay(2000).hide(500);
}
Code is fairly self-explaining, but this will make two functions: generateError and showError.
generateError you need to call before you want to show the error, possibly when the page loads it will add a small header on top of all you other elements and will appear hidden.
showError uses a text argument with the error you want to show. Then it will set the text to the div and show it for two seconds.
This then is more what you are looking for?
$(document).ready(function () {
var input = $("input");
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
input.keypress(function (ele) {
// if regex.test( input ) === false
createErrors(ele.target);
})
});
var createErrors = function (ele) {
$('<span>TEST!</span>').insertAfter(ele);
$("#arrival_date").focus();
};
This works on keypress, that means the regex gets checked every time a key is pressed. It also passes the element where the user is typing as parameter, this means that you wont get errors for all input:text, but only for the ones where there is an error.
Updated Fiddle (still not perfect, but if its an school exercise this will help you to finish it :)

Categories