JQuery Form Submission not Storing Value? - javascript

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();

Related

After completing Validation on input function won't link to the next .html

I created a part of the simple website with a register page I created a validation (.js) for both and wanted to validate the input on the form so after i completed the validation criteria and fill all the input it supposed to link or open the next page (it's login page if you are in the register.html). The problem is if i don't include href to link it, it won't open the next page but the validation was successful but if i include href the validation was skipped and it instantly opens the next page which is login.html after i click on the Register button. How to put validation on the Register button so it validates the input and open the next page at the same time? (A message for a successful registration after that is also better). Here is the code for register and the register validation.
This is called registersraboet.html for the Register page.
<!DOCTYPE html>
<html>
<head>
<title>Register Sraboet</title>
<link rel="stylesheet" type="text/css"
href="css/register.css">
<script type="text/javascript" src="js/jquery-
latest.min.js"></script>
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
</head>
<body>
<div class="headerregister">
<img src="assets/logo.png">
</div>
<div class="containerregister">
<form action="" id="rgs_form">
<div id="err_msg"></div>
<label><b>Email</b></label><br>
<input type="email" placeholder="masukkan email
anda" id="emailrgs"><br>
<label><b>Username</b></label><br>
<input type="text" placeholder="masukkan nama
anda" id="usernamergs"><br>
<label><b>Password</b></label><br>
<input type="password" placeholder="masukkan
password anda" id="passwordrgs"><br>
<label><b>ID Number</b></label><br>
<input type="text" placeholder="masukkan nomor
KTP anda" id="KTPrgs"><br>
<label><b>Phone Number</b></label><br>
<input type="text" placeholder="masukkan nomor
telepon anda" id="phonergs"><br>
<div class="termsnprivacy">
<p>By creating an account you agree to
our Terms & Privacy</p>
</div>
<div class="registerbtn">
<button type="button"
onclick="validatergs()">Register</button><br>
</div>
<div class="alreadyakun">
<br><p>Sudah Punya Akun? Silahkan Login</p>
</div>
</form>
</div>
<div class="footerregister">
<div class="copyrightfooter">
<label for="Copyright">Copyright ©
Sraboet 2020</label>
</div>
</div>
<script type="text/javascript"
src="js/validationregister.js"></script>
</body>
</html>
This is called validationregister.js for the validation in register.
var err = document.getElementById('err_msg');
function validatergs(){
var email = document.getElementById('emailrgs').value;
var username =
document.getElementById('usernamergs').value;
var password =
document.getElementById('passwordrgs').value;
var ktp = document.getElementById('KTPrgs').value;
var phones = document.getElementById('phonergs').value;
if(email == ""){
err.innerHTML = "Email harus diisi!"
}
else if(username == ""){
err.innerHTML = "Nama harus diisi!"
}
else if(password == ""){
err.innerHTML = "Password harus diisi!"
}
else if(ktp == ""){
err.innerHTML = "Nomor ktp harus diisi!"
}
else if(!+(ktp)){
err.innerHTML = "nomor ktp harus angka!";
}
else if(phones == ""){
err.innerHTML = "Nomor telepon harus diisi!"
}
else if(!+(phones)){
err.innerHTML = "Nomor telepon harus angka!";
}
else {
a.href = "loginsraboet.html";
}
}
This is not the right way to write it. First you get the a node, use getelementByclass or some other method to trigger the node click() method such as let a= document.getelementbyid (#a);next a.click ()

How to get alert boxes and validation working on this code

I got this code made but i can't get it to validate the required fields with alert boxes for missing fields or submit to a pop up window like i'm trying to do. The code is supposed to validate certain fields that only show up when one of the radio buttons are clicked and a pop up window containing a url is supposed to show up after submission. Not working. Need help.
Code:
window.onload = function() {
document.getElementById('ifBusiness').style.display='none';
}
function BusinessorResidence() {
if(document.getElementById('businessCheck').checked) {
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 address=document.forms["myForm"]["address"];
var bname=document.forms["myForm"]["bname"];
var url=document.forms["myForm"]["url"];
var id=document.forms["myForm"]["tax"];
var rname=document.forms["myForm"]["rname"];
var email=documen.forms["myForm"]["email"];
if(address.value == "") {
alert("Please enter an address.");
address.focus;
return false;
}
if(bname.value == "") {
alert("Please enter a business name.");
bname.focus;
return false;
}
if(url.value == "") {
alert("Please enter a business URL.");
url.focus;
return false;
}
if(id.value == "") {
alert("Please enter a business tax ID.");
id.focus;
return false;
}
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;
}
return true;
}
<!DOCTYPE html>
<html>
<head>
<title>Javascript Assignment</title>
<center><h1>Fill the form below</h1>
</head>
<body>
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<center><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>Business Name: </b><input type="text" id="name" name="bname"><br>
<b>Business Website URL: </b><input type="text" id="url" name="url"><br>
<b>Business Tax ID: </b><input type="text" id="tax" name="tax"><br>
<input type="submit" value="Submit">
</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"><br>
<input type="submit" value="Submit"></center>
</div>
</form>
<hr>
<hr>
</body>
</html>
The alert boxes are not popping up and I'm not sure how to fix it.
As per the comments, I have added the if-clause checking for business or not.
I also added the code to open the form submission into a new window.
Finally I cleaned up all the things you should not use anymore, like obsolete HTML tags like <b> and <center> and such, adding comments when appropriate.
<!DOCTYPE html>
<html>
<head>
<title>
<h1>Javascript Assignment</h1>
<!-- the titles should be inside the title, not inside the <head> tag -->
<h2>Fill the form below</h2>
</title>
<!-- center tag is deprecated and should be replaced by CSS -->
<style>
head {
text-align: center;
}
.bold {
font-weight: bold;
}
</style>
<!-- script tags should be at the bottom of the body, not inside the <head> -->
</head>
<body>
<form name="myForm" action="http://csit.selu.edu/cgi-bin/echo.cgi" onsubmit="return validateForm()" method="post">
<p>
<span class="bold">Address: </span>
<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">
<span class="bold">Name: </span>
<input type="text" id="name" name="rname">
<br>
<span class="bold">Email: </span>
<input type="text" id="email" name="email">
</div>
<!-- missed the closing </div> -->
</div>
</div>
<!-- Only one submit button per form -->
<input type="submit" value="Submit">
</form>
<hr>
<hr>
<!-- script tags should be at the bottom of the body, not inside the <head> -->
<!-- both scripts can be in the same <script> tag -->
<script>
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 banem, 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;
}
// It does not make sense to call the tax id "id", tax is a better name.
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,statusbar=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' );
// Continue as normal
return true;
}
</script>
</body>
</html>

Basic HTML-Javascript based form validation

I am very new to js and html, could someone help me understand as to why my page is getting redirected to the next page even if the validation fails and my "validate()" function returns only FALSE!
I have created a form that takes name, age, email, state etc as input and it should ideally validate them and then proceed towards the next page.
Here is the code :
<!DOCTYPE html>
<html>
<head>
<title> My first web app </title>
<script type="text/javascript">
function validate(){
var name=document.getElementById('name_id').value;
var email=document.getElementById('email_id').value;
var age=document.getElementById('age_id').value;
var state=document.getElementById('state_id').value;
var address=document.getElementById('address_id').value;
//checking conditions for name
if (name_length<10)
{
return false;
}
if(!(/\w \w/.test(name2)))
{
alert("Please enter name correctly!");
return false;
}
if(/\d/.test(name2))
{
alert("Name cannot contain digits");
return false;
}
//checking conditions for email
var index_of_at = name.indexOf('#');
if(index_of_at == -1)
{
alert("Please enter a valid email address");
return false;
}
else
{
var befor_at = email.substring(0,index_of_at);
var after_at =email.substring(index_of_at+1,email.length);
if(!(/[!-$?]/.test(before_at)))
{
if((/(\w|\d|.)/).test(before_at))
continue;
else
{
alert("Please enter a valid email address");
return false;
}
}
else
{
alert("Please enter a valid email address");
return false;
}
}
//checking conditions for age
if(/\w/.test(age))
{
alert("Please enter a valid Age");
return false;
}
else
{
if(age>100 || age<0)
{
alert("Please enter age btetween 0 and 100");
return false;
}
}
return false;
}
</script>
</head>
<body>
<h1 style = "text-align : center;"> Enter Details </h1>
<form action = "C:\Users\hp\Documents\Orgzit Project\handle.html" method="post" onsubmit="return validate();">
Name:<br>
<input type="text" name="name" id="name_id"><br>
Email:<br>
<input type="text" name="email" id="email_id"><br>
Age:<br>
<input type="text" name="age" id="age_id"><br>
State:<br>
<input type="text" name="state" id="state_id"><br>
Address:<br>
<input type="text" name="address" id="address_id"><br>
Photo: <br>
<input type="img" name="display-picture" id=photo_id>
<br> <br> <br>
<input type="submit" value ="Submit">
</form>
</body>
</html>
Could somebody please help me with why my code redirects directly to handle.html without checking for validations?
You're trying to get the length of name as follow: name_length this is a typo, however, you have another error: a continue keyword
if((/(\w|\d|.)/).test(before_at))
continue;
^
else
Changed to:
if((/(\w|\d|.)/).test(before_at)) {
//continue; You need to modify this part.
} else {
alert("Please enter a valid email address");
return false;
}
You need to understand that continue keyword must be placed within a loop, i.e: for-loop.
<!DOCTYPE html>
<html>
<head>
<title> My first web app </title>
<script type="text/javascript">
function validate(e){
var name=document.getElementById('name_id').value;
var email=document.getElementById('email_id').value;
var age=document.getElementById('age_id').value;
var state=document.getElementById('state_id').value;
var address=document.getElementById('address_id').value;
//checking conditions for name
if (name.length<10)
{
alert('Please enter name correctly!');
return false;
}
if(!(/\w \w/.test(name2)))
{
alert("Please enter name correctly!");
return false;
}
if(/\d/.test(name2))
{
alert("Name cannot contain digits");
return false;
}
//checking conditions for email
var index_of_at = name.indexOf('#');
if(index_of_at == -1)
{
alert("Please enter a valid email address");
return false;
}
else
{
var befor_at = email.substring(0,index_of_at);
var after_at =email.substring(index_of_at+1,email.length);
if(!(/[!-$?]/.test(before_at)))
{
if((/(\w|\d|.)/).test(before_at)) {
//continue;
} else
{
alert("Please enter a valid email address");
return false;
}
}
else
{
alert("Please enter a valid email address");
return false;
}
}
//checking conditions for age
if(/\w/.test(age))
{
alert("Please enter a valid Age");
return false;
}
else
{
if(age>100 || age<0)
{
alert("Please enter age btetween 0 and 100");
return false;
}
}
return false;
}
</script>
</head>
<body>
<h1 style = "text-align : center;"> Enter Details </h1>
<form action = "C:\Users\hp\Documents\Orgzit Project\handle.html" method="post" onsubmit="return validate(event);">
Name:<br>
<input type="text" name="name" id="name_id"><br>
Email:<br>
<input type="text" name="email" id="email_id"><br>
Age:<br>
<input type="text" name="age" id="age_id"><br>
State:<br>
<input type="text" name="state" id="state_id"><br>
Address:<br>
<input type="text" name="address" id="address_id"><br>
Photo: <br>
<input type="img" name="display-picture" id=photo_id>
<br> <br> <br>
<input type="submit" value ="Submit">
</form>
</body>
</html>
If you want to start learning web development with html and javascript, i suggest learn shortest way to do it. For javascript validation check this jquery validation
<!DOCTYPE html>
<html>
<head>
<title> My first web app </title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jquery-validation#1.17.0/dist/jquery.validate.js"></script>
</head>
<body>
<h1 style = "text-align : center;"> Enter Details </h1>
<form action = "C:\Users\hp\Documents\Orgzit Project\handle.html" name="userForm" id="userForm" method="post">
Name:<br>
<input type="text" name="name" id="name_id"><br>
Email:<br>
<input type="text" name="email" id="email_id"><br>
Age:<br>
<input type="text" name="age" id="age_id"><br>
State:<br>
<input type="text" name="state" id="state_id"><br>
Address:<br>
<input type="text" name="address" id="address_id"><br>
Photo: <br>
<input type="img" name="display-picture" id=photo_id>
<br> <br> <br>
<input type="submit" value ="Submit">
</form>
<script type="text/javascript">
$('#userForm').validate({
rules: {
name :{
required : true
},
email: {
required : true,
email : true,
},
age: {
required: true,
minlength:18, // Can define minimum age
maxlength:60 // max page
}
},
submitHandler: function(form) {
alert("All Well") ;
$("#userForm").submit(); // form tag id to sumit the form
return false ;
}
});
</script>
</body>
</html>
With jquery validation you can lots too much work with very short hand code.
Hope this will help, All the best.

Form Validation and Alert issues in 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>

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