I have in HTML, three input fields and one button.
beneath each input I have a span.
Every click on the button triggers a function in which colors the empty field in red,
How can I insert a text to the span beneath the input in case the empty field?
HTML:
<head>
<title>Document</title>
<link rel="stylesheet" href="train.css">
</head>
<body>
<div class="container">
<label for="firstName">First Name</label>
<input type="text" name="" id="firstName">
<span ></span>
<label for="lastName">Last Name</label>
<input type="text" name="" id="lastName">
<span ></span>
<label for="email">Email</label>
<input type="email" name="" id="email">
<span></span>
</div>
<button onclick="showError()"> Show</button>
<script src="train.js"></script>
</body>
</html>
JS
function showError() {
const firstNameEl = document.getElementById("firstName");
const lastNameEl = document.getElementById("lastName");
const emailEl = document.getElementById("email");
let rowsAreFilled = true
let arrayOfAllInfo = [firstNameEl, lastNameEl, emailEl]
for (let i = 0; i < arrayOfAllInfo.length; i++) {
if (arrayOfAllInfo[i].value === "") {
arrayOfAllInfo[i].style.background = "red"
rowsAreFilled = false
}
else {
arrayOfAllInfo[i].style.background = ""
}
}
if (rowsAreFilled === true) {
alert("first name: " + arrayOfAllInfo[0].value + "\n" + "last name: " + arrayOfAllInfo[1].value + "\n" + "email: " + arrayOfAllInfo[2].value)
}
}
You can have the browser enforce required fields for you in a <form> element with the required attribute:
<head>
<title>Document</title>
<link rel="stylesheet" href="train.css">
</head>
<body>
<form class="container">
<label for="firstName">First Name</label>
<input required type="text" name="" id="firstName">
<label for="lastName">Last Name</label>
<input required type="text" name="" id="lastName">
<label for="email">Email</label>
<input required type="email" name="" id="email">
<button> Show</button>
</form>
<script src="train.js"></script>
</body>
You can style the :required and :invalid pseudo classes:
input:required {
placeholder: 'required';
border: 2px solid black;
}
input:invalid:focus {
border: 2px solid red;
background-color: #f004;
}
<head>
<title>Document</title>
<link rel="stylesheet" href="train.css">
</head>
<body>
<form class="container">
<label for="firstName">First Name</label>
<input required type="text" name="" id="firstName">
<label for="lastName">Last Name</label>
<input required type="text" name="" id="lastName">
<label for="email">Email</label>
<input required type="email" name="" id="email">
<button>Show</button>
</form>
<script src="train.js"></script>
</body>
Ok, so the answers above of the kind people didn't really answer the question, I asked how to add a text to the specific span by JavaScript in case of empty field..
Any, this is the answer I got to:
function showError() {
const firstNameEl = document.getElementById("firstName");
const lastNameEl = document.getElementById("lastName");
const emailEl = document.getElementById("email");
const errorOneSpan = document.getElementById("errorOne");
const errorSecSpan = document.getElementById("errorSec");
const errorthreeSpan = document.getElementById("errorthree");
let rowsAreFilled = true
let arrayOfSpans = [errorOneSpan, errorSecSpan, errorthreeSpan ]
let arrayOfAllInfo = [firstNameEl, lastNameEl, emailEl]
for (let i = 0; i < arrayOfAllInfo.length; i++) {
if (arrayOfAllInfo[i].value === "") {
arrayOfAllInfo[i].style.background = "red"
arrayOfSpans[i].innerText = "Error!"
rowsAreFilled = false
}
else {
arrayOfAllInfo[i].style.background = ""
arrayOfSpans[i].innerText = ""
}
}
if (rowsAreFilled === true) {
alert("first name: " + arrayOfAllInfo[0].value + "\n" + "last name: " + arrayOfAllInfo[1].value + "\n" + "email: " + arrayOfAllInfo[2].value)
}
}
Related
I currently have this code https://codepen.io/jammydodger29/pen/RwgaVom where the user inputs their details into the fields and depending if its valid or not the background of the input will change. I am currently having a problem with my card field. The alert will trigger if the card isn't valid telling the user that the card details is wrong but it won't change the colour to pink, constantly remaining green (as if its valid). In addition, after clicking ok on the alert, I can still submit the form even if the card field is still incorrect. The code for this is below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Technical Challenge</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body>
<div class = form>
<form id = "form" form action="mailto:test#test.com" method="POST" enctype="text/plain">
<div class="form-group">
<label id="name-label" for="name">Name:</label>
<input
type="text"
name="name"
id="name"
pattern="[A-Za-z!#$%&'*+-/=?^_`{|}~]+"
title="Please enter a valid name."
class="form-control"
placeholder="Enter Your Name"
required
/>
<br>
<div class="form-group">
<label id="email-label" for="email">Email:</label>
<input
type="email"
name="email"
id="email"
class="form-control"
placeholder="Enter Your Email"
required
/>
<br>
<div class="form-group">
<label id="card-label" for="card">Card:</label>
<input
id="cardInput"
type="text"
size="24"
maxlength="20"
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
name="cc_number"
onblur="
// save input string and strip out non-numbers
cc_number_saved = this.value;
this.value = this.value.replace(/[^\d]/g, '');
if(!checkLuhn(this.value)) {
alert('Sorry, that is not a valid number - please try again!');
}"
" onfocus="
// restore saved string
if(this.value != cc_number_saved) this.value = cc_number_saved;
"
placeholder="Enter a Proxy Credit Card Number."
required
/>
<br>
<div class="form-group">
<button type="submit" id="submit" class="submit-button">
Submit
</button>
</form>
</div>
</body>
</html>
input:required:valid, input:focus:valid {
background-color: rgb(137,200,46);
border: rgb(60,60,59);
}
input:not(:focus):not(:placeholder-shown):invalid {
background-color: rgb(231,0,100);
border: rgb(60,60,59);
}
function checkLuhn(input)
{
var sum = 0;
var numdigits = input.length;
var parity = numdigits % 2;
for(var i=0; i < numdigits; i++) {
var digit = parseInt(input.charAt(i))
if(i % 2 == parity) digit *= 2;
if(digit > 9) digit -= 9;
sum += digit;
}
return (sum % 10) == 0;
}
Any help with this would be really appreciated.
I don't know what a valid number input looks like so I will leave checking of that part to you. I extracted your inline js to external js file because such a big amount of inline js hinders readability. Aside from that, you can use formDOM.checkValidity() to check if all the fields of a form are valid and
you can also use field.setCustomValidity() to set a field to invalid.
function checkLuhn(input)
{
var sum = 0;
var numdigits = input.length;
var parity = numdigits % 2;
for(var i=0; i < numdigits; i++) {
var digit = parseInt(input.charAt(i))
if(i % 2 == parity) digit *= 2;
if(digit > 9) digit -= 9;
sum += digit;
}
return (sum % 10) == 0;
}
let cc_number_saved = "";
function onBlurEvent(mythis) {
cc_number_saved = mythis.value;
mythis.value = mythis.value.replace(/[^\d]/g, '');
if(!checkLuhn(mythis.value)) {
alert('Sorry, that is not a valid number - please try again!');
}
mythis.setCustomValidity("Invalid field");
}
function onFocusEvent(mythis) {
// restore saved string
// What is this for?
if(mythis.value != cc_number_saved) mythis.value = cc_number_saved;
}
function onSubmitEvent(mythis) {
if (!mythis.checkValidity()) {
event.preventDefault();
}
}
input:required:valid, input:focus:valid {
background-color: rgb(137,200,46);
border: rgb(60,60,59);
}
input:not(:focus):not(:placeholder-shown):invalid {
background-color: rgb(231,0,100);
border: rgb(60,60,59);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Technical Challenge</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body>
<div class = form>
<form id = "form" form action="mailto:test#test.com" method="POST" enctype="text/plain">
<div class="form-group">
<label id="name-label" for="name">Name:</label>
<input
type="text"
name="name"
id="name"
pattern="[A-Za-z!#$%&'*+-/=?^_`{|}~]+"
title="Please enter a valid name."
class="form-control"
placeholder="Enter Your Name"
required
/>
<br>
<div class="form-group">
<label id="email-label" for="email">Email:</label>
<input
type="email"
name="email"
id="email"
class="form-control"
placeholder="Enter Your Email"
required
/>
<br>
<div class="form-group">
<label id="card-label" for="card">Card:</label>
<input
id="cardInput"
type="text"
size="24"
maxlength="20"
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
name="cc_number"
onblur="onBlurEvent(this)"
onfocus="onFocusEvent(this)"
placeholder="Enter a Proxy Credit Card Number."
required
/>
<br>
<div class="form-group">
<button onsubmit"onSubmitEvent(this)" type="submit" id="submit" class="submit-button">
Submit
</button>
</form>
</div>
</body>
</html>
I currently have this code:
function checkLuhn(input)
{
var sum = 0;
var numdigits = input.length;
var parity = numdigits % 2;
for(var i=0; i < numdigits; i++) {
var digit = parseInt(input.charAt(i))
if(i % 2 == parity) digit *= 2;
if(digit > 9) digit -= 9;
sum += digit;
}
return (sum % 10) == 0;
}
let cc_number_saved = "";
function onBlurEvent(mythis) {
cc_number_saved = mythis.value;
mythis.value = mythis.value.replace(/[^\d]/g, '');
if(!checkLuhn(mythis.value)) {
alert('Sorry, that is not a valid number - please try again!');
}
mythis.setCustomValidity("Invalid field");
}
function onFocusEvent(mythis) {
// restore saved string
// What is this for?
if(mythis.value != cc_number_saved) mythis.value = cc_number_saved;
}
function onSubmitEvent(mythis) {
if (!mythis.checkValidity()) {
event.preventDefault();
}
}
input:required:valid, input:focus:valid {
background-color: rgb(137,200,46);
border: rgb(60,60,59);
}
input:not(:focus):not(:placeholder-shown):invalid {
background-color: rgb(231,0,100);
border: rgb(60,60,59);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Technical Challenge</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body>
<div class = form>
<form id = "form" form action="mailto:test#test.com" method="POST" enctype="text/plain">
<div class="form-group">
<label id="name-label" for="name">Name:</label>
<input
type="text"
name="name"
id="name"
pattern="[A-Za-z!#$%&'*+-/=?^_`{|}~]+"
title="Please enter a valid name."
class="form-control"
placeholder="Enter Your Name"
required
/>
<br>
<div class="form-group">
<label id="email-label" for="email">Email:</label>
<input
type="email"
name="email"
id="email"
class="form-control"
placeholder="Enter Your Email"
required
/>
<br>
<div class="form-group">
<label id="card-label" for="card">Card:</label>
<input
id="cardInput"
type="text"
size="24"
maxlength="20"
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
name="cc_number"
onblur="onBlurEvent(this)"
onfocus="onFocusEvent(this)"
placeholder="Enter a Proxy Credit Card Number."
required
/>
<br>
<div class="form-group">
<button onsubmit"onSubmitEvent(this)" type="submit" id="submit" class="submit-button">
Submit
</button>
</form>
</div>
</body>
</html>
Currently this code will turn any card input details to red regardless if they are valid (I was previously having problems as detailed here Changing Input background colour on invalid. However I know that 4111-1111-1111-1111 for example is a valid card number yet the input field will turn red and not allow me to submit the form. My question is how would I go about changing my current code to allow 4111-1111-1111-1111 as well as other valid card numbers to be accepted?
You need to make sure you only set setCustomValidity if it is really invalid, and if not set it back to blank string
function onBlurEvent(mythis) {
cc_number_saved = mythis.value;
mythis.value = mythis.value.replace(/[^\d]/g, '');
if(!checkLuhn(mythis.value)) {
alert('Sorry, that is not a valid number - please try again!');
mythis.setCustomValidity("Invalid field");
return;// make sure you return here!!
}
mythis.setCustomValidity("");
}
Working example:
function checkLuhn(input)
{
var sum = 0;
var numdigits = input.length;
var parity = numdigits % 2;
for(var i=0; i < numdigits; i++) {
var digit = parseInt(input.charAt(i))
if(i % 2 == parity) digit *= 2;
if(digit > 9) digit -= 9;
sum += digit;
}
return (sum % 10) == 0;
}
let cc_number_saved = "";
function onBlurEvent(mythis) {
cc_number_saved = mythis.value;
mythis.value = mythis.value.replace(/[^\d]/g, '');
if(!checkLuhn(mythis.value)) {
alert('Sorry, that is not a valid number - please try again!');
mythis.setCustomValidity("Invalid field");
return;
}
mythis.setCustomValidity("");
}
function onFocusEvent(mythis) {
// restore saved string
// What is this for?
if(mythis.value != cc_number_saved) mythis.value = cc_number_saved;
}
function onSubmitEvent(mythis) {
if (!mythis.checkValidity()) {
event.preventDefault();
}
}
input:required:valid, input:focus:valid {
background-color: rgb(137,200,46);
border: rgb(60,60,59);
}
input:not(:focus):not(:placeholder-shown):invalid {
background-color: rgb(231,0,100);
border: rgb(60,60,59);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Technical Challenge</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body>
<div class = form>
<form id = "form" form action="mailto:test#test.com" method="POST" enctype="text/plain">
<div class="form-group">
<label id="name-label" for="name">Name:</label>
<input
type="text"
name="name"
id="name"
pattern="[A-Za-z!#$%&'*+-/=?^_`{|}~]+"
title="Please enter a valid name."
class="form-control"
placeholder="Enter Your Name"
required
/>
<br>
<div class="form-group">
<label id="email-label" for="email">Email:</label>
<input
type="email"
name="email"
id="email"
class="form-control"
placeholder="Enter Your Email"
required
/>
<br>
<div class="form-group">
<label id="card-label" for="card">Card:</label>
<input
id="cardInput"
type="text"
size="24"
maxlength="20"
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
name="cc_number"
onblur="onBlurEvent(this)"
onfocus="onFocusEvent(this)"
placeholder="Enter a Proxy Credit Card Number."
required
/>
<br>
<div class="form-group">
<button onsubmit"onSubmitEvent(this)" type="submit" id="submit" class="submit-button">
Submit
</button>
</form>
</div>
</body>
</html>
I changed your condition in checkLuhn function to make sure that when it is true it shows green, else it is red:
if(checkLuhn(mythis.value)) {
mythis.setCustomValidity('');
}
else{
alert('Sorry, that is not a valid number - please try again!');
mythis.setCustomValidity("Invalid field");
}
This is what you mostly forgot: mythis.setCustomValidity(''); to make sure it is valid
DEMO
function checkLuhn(input)
{
var sum = 0;
var numdigits = input.length;
var parity = numdigits % 2;
for(var i=0; i < numdigits; i++) {
var digit = parseInt(input.charAt(i))
if(i % 2 == parity) digit *= 2;
if(digit > 9) digit -= 9;
sum += digit;
}
return (sum % 10) == 0;
}
let cc_number_saved = "";
function onBlurEvent(mythis) {
cc_number_saved = mythis.value;
mythis.value = mythis.value.replace(/[^\d]/g, '');
if(checkLuhn(mythis.value)) {
mythis.setCustomValidity('');
}
else{
alert('Sorry, that is not a valid number - please try again!');
mythis.setCustomValidity("Invalid field");
}
}
function onFocusEvent(mythis) {
// restore saved string
// What is this for?
if(mythis.value != cc_number_saved) mythis.value = cc_number_saved;
}
function onSubmitEvent(mythis) {
if (!mythis.checkValidity()) {
event.preventDefault();
}
}
input:required:valid, input:focus:valid {
background-color: rgb(137,200,46);
border: rgb(60,60,59);
}
input:not(:focus):not(:placeholder-shown):invalid {
background-color: rgb(231,0,100);
border: rgb(60,60,59);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Technical Challenge</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body>
<div class = form>
<form id = "form" form action="mailto:test#test.com" method="POST" enctype="text/plain">
<div class="form-group">
<label id="name-label" for="name">Name:</label>
<input
type="text"
name="name"
id="name"
pattern="[A-Za-z!#$%&'*+-/=?^_`{|}~]+"
title="Please enter a valid name."
class="form-control"
placeholder="Enter Your Name"
required
/>
<br>
<div class="form-group">
<label id="email-label" for="email">Email:</label>
<input
type="email"
name="email"
id="email"
class="form-control"
placeholder="Enter Your Email"
required
/>
<br>
<div class="form-group">
<label id="card-label" for="card">Card:</label>
<input
id="cardInput"
type="text"
size="24"
maxlength="20"
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');"
name="cc_number"
onblur="onBlurEvent(this)"
onfocus="onFocusEvent(this)"
placeholder="Enter a Proxy Credit Card Number."
required
/>
<br>
<div class="form-group">
<button onsubmit"onSubmitEvent(this)" type="submit" id="submit" class="submit-button">
Submit
</button>
</form>
</div>
</body>
</html>
I'm creating a simple form that allows you to enter data that will then be sent to a DB. In particular I need to know from you how I can create a dynamic form that allows me to enter a number of people specified by the user. Basically if the user wants to add 3 people must present 3 new fields to enter Name, Surname and email, if he wants to add 5, 5 new fields.
I write this, but in my index.php it doesn't work.
// Funzione che permette di aggiungere elementi al form (in questo caso rate)
function Aggiungipersone(person) {
var numero_persone = person.value;
var box = document.getElementById('box_person');
if (numero_persone == "") {
box.innerHTML = '';
} else {
if (isNaN(numero_persone) == true) {
box.innerHTML = '';
} else {
var righe = "";
// Inserisco una riga ad ogni ciclo
for (i = 1; i <= numero_persone; i++) {
righe = righe + "Persona n°" + i + " : <input type='text' name='iname" + i + " size='10' value='" + Cognome + "' type='text' name='isurname' size='10' value=''/><br/>";
}
// Aggiorno il contenuto del box che conterrĂ gli elementi aggiunti
box.innerHTML = righe;
}
}
}
Inserire i dati richiesti:<br><br>
<form method="post" action="input.php">
<b> Richiedente Conferenza:</b><br><br> Nome:
<input type="text" name="name" size="20"><br> Cognome:
<input type="text" name="surname" size="20"><br> Email: <input type="email" name="email" size="20"><br> Oggetto Conferenza:<br><textarea name="testo" rows="5" cols="40" placeholder="Specificare oggetto Videoconferenza"></textarea><br>
</form>
UPDATE
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Prenotazione Videoconferenza</title>
<script src="utils.js"></script>
</head>
<body>
<?php
$( document ).ready(function() {
$("#add").click(function(){
var val1 =$("#n1").val();
for(var i=0;i<val1;i++){
$("#start").append($("#first").clone());
}
});
});
?>
Inserire i dati richiesti:<br><br>
<form method="post" action="input.php">
<b> Richiedente Conferenza:</b><br><br>
Nome:<input type="text" name="name" size="20"><br>
Cognome:<input type="text" name="surname" size="20"><br>
Email: <input type="email" name="email" size="20"><br>
Oggetto Conferenza:<br><textarea name="testo" rows="5" cols="40" placeholder="Specificare oggetto Videoconferenza"></textarea><br>
</form>
</body>
</html>
In the utilis.js i inserted:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="n1" value="1"><br>
Add
<div id="start">
<div id="first">
Nome:<input type="text" name="name" size="20"><br> Cognome:
<input type="text" name="surname" size="20"><br> Email: <input type="email" name="email" size="20"><br>
<br>
</div>
</div>
// content of external javascript file:
$(document).ready(function() {
$("#add").click(function(e) {
e.preventDefault(); // stop the link
var val1 = $("#n1").val();
for (var i = 0; i < val1; i++) {
$("#start").append($("#first").clone());
}
});
});
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Prenotazione Videoconferenza</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- here is the external file -->
<script src="utils.js"></script>
</head>
<body>
<input type="text" id="n1" value="1"><br>
Add
<div id="start">
<div id="first">
Nome:<input type="text" name="name[]" size="20"><br> Cognome:
<input type="text" name="surname[]" size="20"><br> Email: <input type="email" name="email[]" size="20"><br>
<br>
</div>
</div>
</body>
</html>
once you submit form then you will get array into php file and you can access like this
if($_POST['name']){ foreach($_POST['name'] as $name) { echo $name; } }
1) With VueJS - demo on code pen
2) JQuery
const tmpl = $('#tmpl').html().trim()
$('#btn-add').click(() => {
let peopleCount = +$('#people-count').val(),
html = Array(peopleCount)
.fill(tmpl)
.join('')
$('#form-items').append(html)
})
$('#form')
.submit(() => {
alert('Submit form by ajax or remove this mathod for default behavior')
return false;
})
.delegate('.btn-del', {
click() {
$(this).closest('.row').remove()
},
})
<div id="app">
<div>
<div>
<button id="btn-add">Add new user</button>
<label>Number of People:</label>
<input type="number" id="people-count" value="1" min="1">
</div>
<form id="form">
<div id="form-items" data-empty="Users list is empty"></div>
<button>Send</button>
</form>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/x-template" id="tmpl">
<div class="row">
<label>
Name:
<input class="people" name="name[]">
</label>
<label>
Surname:
<input class="people" name="surname[]">
</label>
<label>
Email:
<input type="email" class="people" name="email[]">
</label>
<button class="btn-del">Delete</button>
</div>
</script>
<style>
.people {
width: 80px;
}
#form-items:empty + button {
display: none;
}
#form-items:empty:before {
content: attr(data-empty);
display: block;
}
</style>
you will need something like this:
$("#people").on("keyup", function() {
$("#form").html(""); // clear the form
var people = $(this).val();
for(i=1;i<=people;i++) {
$("#form").append("<input type='text' name='name[]' placeholder='Name Person "+i+"'><br>");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Number of People:</label>
<input type="number" id="people">
<div id="form"></div>
as you see the input names are with [] which means they are arrays.. That means on your server side script you will recieve an array where you have to go through via
foreach($_POST["names"] as $name) {
// do whatever
}
I am currently creating a signup form for a client and one of the requirements is for the form to be able to transmit and store data offline. I have already tried to work with a database, but I am still in beginning stages learning php so I decided t quit while I am behind.
I found another method of storign data locally suing localstorage with JS, but I am unable to display the stored data in a dynamic table.
Any help on this matter would be greatky appreciated, here is the code I have so far
<!DOCTYPE html>
<html lang="en">
<head>
<title>CIVIC Registration Form</title>
<link rel="icon" href="civic.ico" type="image/x-icon">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/custom.css">
<link rel="stylesheet" href="css/styles.css">
<style>
p.finePrint {
color:#818185;
font-size:70%;
}
</style>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script type="text/javascript">
(function()
{
var Applicant = {
fname: "",
lname: "",
age: 0,
phonenum: "",
email: ""
};
var storageLogic = {
saveItem: function (){
var lscount = localStorage.length;
var inputs = document.getElementsByClassName("form-control");
Applicant.fname = inputs[0].value;
Applicant.lname = inputs[1].value;
Applicant.age = inputs[2].value;
Applicant.phonenum = inputs[3].value;
Applicant.email = inputs[4].value;
localStorage.setItem("Applicant_" + lscount, JSON.stringify(Applicant));
location.reload();
},
loaddata: function() {
var datacount = localStorage.length;
if (datacount > 0)
{
var render = "<table border='1'>";
render += "<tr><th>First Name</th><th>Last Name</th><th>Age</th>" +
"<th>Phone Number</th><th>Email</th>";
for (i=0; i < datacount; i++) {
var key = localStorage.key(i);
var applicant = localStorage.getItem(key);
var data = JSON.parse(applicant);
render += "<tr><td>" + data.fname + "</td><td>" + data.lname + "</td>";
render += "<td>" + data.age + "</td>";
render += "<td>" + data.phonenum + "</td>";
render += "<td>" + data.email + "</td>";
}
render += "</table>";
var newTable = document.getElementById("dvContainer");
newTable.innerHTML = render;
}
}
};
var btnsubmit = document.getElementById('btnsubmit');
btnsubmit.addEventListener('click', storageLogic.saveItem(), false);
window.onload = function() {
storageLogic.loaddata();
};
})();
</script>
</head>
<body>
<div class="container">
<h2 style="color:#005E28"><img src="civic.jpg" height="50" width="50"></img>CIVIC Registration Form</h2>
<form role="form">
<div class="form-group">
<label for="fname">First Name:</label>
<input type="text" class="form-control" id="fname" placeholder="First Name">
</div>
<div class="form-group">
<label for="lname">Last Name:</label>
<input type="text" class="form-control" id="lname" placeholder="Last Name">
</div>
<div class="form-inline">
<label for="age">Age: <input type="text" class="form-control" id="age" placeholder="Age"></label>
<label for="phone">Phone Number: <input type="text" class="form-control" id="phonenum" placeholder="Phone Number"></label>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email">
</div>
<div>
<!-- <button type="submit" class="btn btn-default">Submit</button> -->
<input id="btnsubmit" type="button" value="Submit" class="btn btn-success"/>
<p class="finePrint">*By submitting this form you agree to receiving emails regarding
upcoming events and other information from CIVIC Ontario.
If you have any questions or concerns, please email civicontario#gmail.com*</p>
</div>
</form>
</div>
<div id="dvContainer" class="conatiner">
</div>
</body>
</html>
There are primarily two errors you need to fix:
Move the getElementById() and addEventListener() for id btnsubmit to your onload handler. The way it is now, it tries to find the element before it is actually in the DOM.
You are accidentally invoking the handler that is the second parameter of addEventListener(). In other words, get rid of the () after the second parameter.
Here is a version of your code with those changes that seems to minimally work.
<!DOCTYPE html>
<html lang="en">
<head>
<title>CIVIC Registration Form</title>
<link rel="icon" href="civic.ico" type="image/x-icon">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/custom.css">
<link rel="stylesheet" href="css/styles.css">
<style>
p.finePrint {
color:#818185;
font-size:70%;
}
</style>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> </script>
<script type="text/javascript">
(function()
{
var Applicant = {
fname: "",
lname: "",
age: 0,
phonenum: "",
email: ""
};
var storageLogic = {
saveItem: function (){
var lscount = localStorage.length;
var inputs = document.getElementsByClassName("form-control");
Applicant.fname = inputs[0].value;
Applicant.lname = inputs[1].value;
Applicant.age = inputs[2].value;
Applicant.phonenum = inputs[3].value;
Applicant.email = inputs[4].value;
localStorage.setItem("Applicant_" + lscount, JSON.stringify(Applicant));
location.reload();
},
loaddata: function() {
var datacount = localStorage.length;
if (datacount > 0)
{
var render = "<table border='1'>";
render += "<tr><th>First Name</th><th>Last Name</th><th>Age</th>" +
"<th>Phone Number</th><th>Email</th>";
for (i=0; i < datacount; i++) {
var key = localStorage.key(i);
var applicant = localStorage.getItem(key);
var data = JSON.parse(applicant);
render += "<tr><td>" + data.fname + "</td><td>" + data.lname + "</td>";
render += "<td>" + data.age + "</td>";
render += "<td>" + data.phonenum + "</td>";
render += "<td>" + data.email + "</td>";
}
render += "</table>";
var newTable = document.getElementById("dvContainer");
newTable.innerHTML = render;
}
}
};
window.onload = function() {
storageLogic.loaddata();
var btnsubmit = document.getElementById('btnsubmit');
btnsubmit.addEventListener('click', storageLogic.saveItem, false);
};
})();
</script>
</head>
<body>
<div class="container">
<h2 style="color:#005E28"><img src="civic.jpg" height="50" width="50"></img>CIVIC Registration Form</h2>
<form role="form">
<div class="form-group">
<label for="fname">First Name:</label>
<input type="text" class="form-control" id="fname" placeholder="First Name">
</div>
<div class="form-group">
<label for="lname">Last Name:</label>
<input type="text" class="form-control" id="lname" placeholder="Last Name">
</div>
<div class="form-inline">
<label for="age">Age: <input type="text" class="form-control" id="age" placeholder="Age"></label>
<label for="phone">Phone Number: <input type="text" class="form-control" id="phonenum" placeholder="Phone Number"></label>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" placeholder="Enter email">
</div>
<div>
<!-- <button type="submit" class="btn btn-default">Submit</button> -->
<input id="btnsubmit" type="button" value="Submit" class="btn btn-success"/>
<p class="finePrint">*By submitting this form you agree to receiving emails regarding
upcoming events and other information from CIVIC Ontario.
If you have any questions or concerns, please email civicontario#gmail.com*</p>
</div>
</form>
</div>
<div id="dvContainer" class="conatiner">
</div>
</body>
</html>
Can anyone see where I could be making a mistake? The form text-box background colors are originally set to grey. If the user makes a mistake I want to turn them yellow with a red border. The function is sort of working, because the form is not going to the server when the form is filled out incorrectly. But the css doesn't change. If I comment out my js call it will post to the server. Here are the snippets:
CSS:
.invalid{
background-color:#ff9;
border: 2px red inset;
}
.reqd{
background-color:#222222;
color:#555555; border-style: solid;
border-color:#555555;
border-width: 1px;
}
HTML:
<!DOCTYPE html>
<?php
// Debug
error_reporting(E_ALL);
?>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="styles.css" type="text/css">
<script src="js/jquery-1.7.2.min.js"></script>
<script src="js/regauth.js"></script>
<title></title>
</head>
<body id="registerBody">
<section id="registerBox">
<form id="registerForm" method="post" action="regauth.php">
<p>Welcome to the atlas registraton! Please fill out the information below.</p>
<br>
<p><label for="firstName">First Name: <input type="text" size="30" id="firstName" name="firstName" class="reqd"></label></p>
<p><label for="lastName">Last Name: <input type="text" size="30" id="lastName" name="lastName" class="reqd"></label></p>
<p><label for="email">Email: <input type="text" size="30" id="email" name="email" class="reqd"></label></p>
<br>
<br>
<p><label for="reqUsername">Username: <input type="text" size="30" id="reqUsername" name="reqUsername" class="reqd"></label></p>
<p><label for="passOne">Password: <input type="password" size="30" id="passOne" name="passOne" class="reqd"></label></p>
<p><label for="passTwo">Confirm Password: <input type="password" size="30" id="passTwo" name="passTwo" class="reqd"></label></p>
<br>
<br>
<p><input type="submit" value="Submit"> <input type="reset" value="Reset Form" class="reset"></p>
</form>
</section>
<script type="text/javascript">
$("#registerBox").css("margin-left", ($(window).width()-425)/2);
$("#registerBox").css("margin-top", ($(document).height()-500)/2);
$('#registerBox').fadeIn(1500);
</script>
</body>
</html>
JS (regauth.js): Courtesy of Tom Negrino, Visual Quickstart Guide: Javascript Eighth Edition
window.onload = initForms;
//Function loops through each form. For each one it adds an event handler to that forms 'onSubmit'.
function initForms() {
for (var i = 0; i < document.forms.length; i++) {
document.forms[i].onsubmit = validForm;
}
}
function validForm() {
var allGood = true;
var allTags = document.getElementsByTagName("*");
for (var i = 0; i < allTags.length; i++) {
if (!validTag(allTags[i])) {
allGood = false;
}
}
return allGood;
function validTag(thisTag) {
var outClass = "";
var allClasses = thisTag.className.split(" ");
for (var j = 0; j < allClasses.length; j++) {
outClass += validBasedOnClass(allClasses[j]) + " ";
}
thisTag.className = outClass;
if (outClass.indexOf("invalid") > -1) {
thisTag.focus();
if (thisTag.nodeName == "INPUT") {
thisTag.select();
}
return false;
}
return true;
function validBasedOnClass(thisClass) {
var classBack = "";
switch (thisClass) {
case "":
case "invalid":
break;
case "reqd":
if (allGood && thisTag.value == "") {
classBack = "invalid ";
}
classBack += thisClass;
break;
default:
classBack += thisClass;
}
return classBack;
}
}
}
Move the "invalid" CSS block to after the "reqd" one.
The rules for CSS are that the "last rule wins" (sort-of; it's more complicated but in this case that's the issue).
Even though the "invalid" rules apply to the invalid elements, because the "reqd" rule has a background color and because it comes after the "invalid" rule, that setting applies.