innerHTML is null? JS Form Validation - javascript

Why i get this error?
I'm using window.onload, i don't understand ... Can you help me?
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Pràctica DOM3</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/zxcvbn/4.2.0/zxcvbn.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/zxcvbn/4.2.0/zxcvbn.js"></script>
<script type="text/javascript" src="script.js"></script>
<style>
h2 {
text-align: center;
border-bottom: 1px solid black;
padding-bottom: 20px;
/*text-decoration: underline;*/
}
#ultimsEstudisCursatsLabel {
margin-top: 10px;
}
#submitFormButton {
margin: auto;
display: block;
}
#resetFormButton {
margin: auto;
display: block;
}
meter {
margin: 0 auto 1em;
width: 100%;
height: .5em;
}
meter[value="1"]::-webkit-meter-optimum-value { background: red; }
meter[value="2"]::-webkit-meter-optimum-value { background: yellow; }
meter[value="3"]::-webkit-meter-optimum-value { background: orange; }
meter[value="4"]::-webkit-meter-optimum-value { background: green; }
</style>
</head>
<body>
<div class="container">
<h2>Inscripció CF Informàtica Marianao</h2>
<br>
<form method="post" action="#" id="formulari">
<div class="form-group">
<label class="control-label col-sm-2" for="input1">Nom</label>
<div class="col-sm-10">
<input type="text" name="nom" class="form-control" id="inputNom" placeholder="Escriu el teu nom ..." />
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Primer cognom</label>
<div class="col-sm-10">
<input type="text" name="primerCognom" class="form-control" id="inputCognom1" placeholder="Escriu el primer cognom ..." />
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Segon cognom</label>
<div class="col-sm-10">
<input type="text" name="segonCognom" class="form-control" id="inputCognom2" placeholder="Escriu el segon cognom ..." />
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Data naixament </label>
<div class="col-sm-10">
<input type="date" name="dataNaixement" class="form-control" id="inputNaixament" placeholder="Selecciona la teva data de naixament ..."/>
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Email </label>
<div class="col-sm-10">
<input type="email" name="email" class="form-control" id="inputEmail" placeholder="Escriu el teu correu electrònic ..."/>
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Telèfon</label>
<div class="col-sm-10">
<input type="tel" name="telefon" class="form-control" id="inputTelefon" placeholder="Escriu el teu telèfon ..."/>
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">DNI</label>
<div class="col-sm-10">
<input type="text" name="dni" class="form-control" id="inputDni" placeholder="Escriu el teu DNI ..." />
<br />
</div>
</div>
<div class="form-group">
<label class="form-label col-sm-2">Cicle formatiu</label>
<div class="col-sm-10">
<select class="form-control" name="cicleFormatiu">
<option value="smx">SMX: Sistemes Microinformàtics i Xarxes</option>
<option value="asix">ASIX: Administració de Sistemes Informàtics en Xarxa</option>
<option value="dam">DAM: Desenvolupament d'Aplicacions Multiplataforma</option>
<option value="daw">DAW: Desenvolupament d'Aplicacions Web</option>
</select>
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" id="ultimsEstudisCursatsLabel">Últims estudis cursats</label>
<div class="col-sm-10">
<div class="radio">
<label><input type="radio" name="ultimEstudis" value="eso" class="custom-control-input">ESO</label><br><br>
</div>
<div class="radio">
<label><input type="radio" name="ultimEstudis" value="batx" class="custom-control-input">Batxillerat</label><br><br>
</div>
<div class="radio">
<label><input type="radio" name="ultimEstudis" value="cfgm" class="custom-control-input">CF Grau Mitjà</label><br><br>
</div>
<div class="radio">
<label><input type="radio" name="ultimEstudis" value="cfgs">CF Grau Superior</label><br><br>
</div>
<div class="radio">
<label><input type="radio" name="ultimEstudis" value="altres">Altres</label><br><br>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Usuari</label>
<div class="col-sm-10">
<input class="form-control" type="text" id="inputUsuari" name="usuari" />
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Contrasenya</label>
<div class="col-sm-10">
<input type="password" id="password" name="contrasenya" class="form-control" />
<meter max="4" id="password-strength-meter"></meter>
<p id="password-strength-text"></p>
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Torna a escriure la contrasenya</label>
<div class="col-sm-10">
<input type="password" name="contrasenyaCheck" id="contrasenyaCheck" class="form-control" disabled/>
<meter max="4" id="password-strength-meter"></meter>
<p id="password-strength-text"></p>
<br />
</div>
<br />
</div>
<div class="form-group">
<label class="control-label col-sm-2">Observacions</label>
<div class="col-sm-10">
<textarea class="form-control" name="observacions" id="textarea" maxlength="500"></textarea>
<br />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Termes i condicions</label>
<div class="col-sm-10">
<label class="checkbox-inline"><input type="checkbox" name="termesCondicions" value="yes" class="form-check-input" >Consulta <span>aquí</span> els termes i condicions.<br></label>
<br />
<br />
<br />
</div>
</div>
<div class="form-group">
<input type="submit" value="Submit Form" class="btn btn-success" id="submitFormButton">
</div>
<div class="form-group">
<input type="reset" value="Reset Form" class="btn btn-primary" id="resetFormButton">
</div>
</form>
</div>
</body>
</html>
JS:
function main (){
var inputNom = document.getElementById("inputNom").addEventListener("blur", validarNomCognoms);
var inputCognom1 = document.getElementById("inputCognom1").addEventListener("blur", validarNomCognoms);
var inputCognom2 = document.getElementById("inputCognom2").addEventListener("blur", validarNomCognoms);
var inputNaixament = document.getElementById("inputNaixament").addEventListener("blur", validarData);
var inputEmail = document.getElementById("inputEmail").addEventListener("blur", validarEmail);
var inputTelefon = document.getElementById("inputTelefon").addEventListener("blur", validarTelefon);
var inputDni = document.getElementById("inputDni").addEventListener("blur", validarDni);
var inputUsuari = document.getElementById("inputUsuari").addEventListener("blur", validarUsuari);
var password = document.getElementById("password").addEventListener("blur", validaContrassenya);
// Recuento de carácteres en el text area.
var textAreaID = document.getElementById("textarea");
var length = textAreaID.getAttribute("maxlength");
var textAreaCount = document.getElementById("count");
textAreaCount.innerHTML = length + " caràcters restants.";
textAreaID.addEventListener ("keypress", function () {
document.getElementById("count").innerHTML = (length - this.value.length) + " caràcters restants.";
});
// Barra de seguridad METER.
document.addEventListener("keydown", function () {
var strength = {
0: "Molt feble.",
1: "Feble.",
2: "Acceptable.",
3: "Forta.",
4: "Molt forta."
}
var password = document.getElementById('password');
var meter = document.getElementById('password-strength-meter');
var text = document.getElementById('password-strength-text');
password.addEventListener('input', function() {
var val = password.value;
var result = zxcvbn(val);
meter.value = result.score;
if(val !== "") {
text.innerHTML = "<strong>" + strength[result.score] + "</strong>";
}
else {
text.innerHTML = "";
}
if (meter.value >= 2) {
document.getElementById("contrasenyaCheck").disabled = false;
}
else {
document.getElementById("contrasenyaCheck").disabled = true;
document.getElementById('contrasenyaCheck').value = "";
}
});
});
// VALIDACIONES.
// Primera validación.
function validarNomCognoms () {
var pattern = /^[a-zA-Z]*$/;
if (this.value.length > 0) {
if(!this.value.match(pattern)) {
this.setCustomValidity("No pot contindre números!");
this.reportValidity();
}
else {
this.setCustomValidity("");
}
}
else {
this.setCustomValidity("No pot citear buit ");
this.reportValidity();
}
}
// Segunda validación.
function validarData () {
if (this.value != "") {
var dataRecibida = this.value;
dataRecibida = dataRecibida.split("-").reverse().join("-");
// Obtener la fecha actual.
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var today = dd + '/' + mm + '/' + yyyy;
if (dataRecibida > today) {
alert ("Data incorrecta.");
}
//this.value.setCustomValidity("");
}
else {
alert ("citeá vacío.");
}
}
// Tercera validación.
function validarEmail () {
if (this.value != "") {
var emailPattern = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,4})+$/;
if (emailPattern.test(this.value)) {
return;
}
else {
alert ("Mail incorrecte.");
}
}
else {
alert ("Está vacío.");
}
}
// Cuarta validación.
function validarTelefon () {
if (this.value != "") {
var emailPattern = /^\d{9}$/;
if (emailPattern.test(this.value)) {
return;
}
else {
alert ("Telèfon incorrecte.");
}
}
else {
alert ("Está vacío.");
}
}
// Quinta validación.
function validarDni () {
if (this.value != "") {
var emailPattern = /^\d{8}[A-Z]$/;
if (emailPattern.test(this.value)) {
var lletres = ['T', 'R', 'W', 'A',
'G', 'M', 'Y', 'F',
'P', 'D', 'X', 'B',
'N', 'J', 'Z', 'S',
'Q', 'V', 'H', 'L',
'C', 'K', 'E', 'T'];
var index = this.value % 23;
var my_array = this.value;
var last_element = my_array[my_array.length - 1];
var boolean = false;
for (var i = 0; i < lletres.length; i++) {
if (last_element == lletres[i]) {
boolean = true;
}
}
if (boolean) {
return;
}
else {
alert ("Lletra DNI incorrecte.");
}
}
else {
alert ("DNI incorrecte.");
}
}
else {
alert ("Está vacío.");
}
}
// Sexta validación.
function validarUsuari () {
if (this.value != "") {
if (this.value.length < 5) {
alert ("Longitud mínima de 5 caràcters.");
}
else if (this.value.length > 12) {
alert ("Longitud màxima de 12 caràcters.");
}
else {
return;
}
}
else {
alert ("Está vacío.");
}
}
// Seéptima validación.
function validaContrassenya () {
var meter = document.getElementById('password-strength-meter');
if (meter.value < 2) {
document.getElementById("cite9").style.display = "block";
}
else {
document.getElementById("cite9").style.display = "none";
}
}
}
window.onload = main;
Thanks guys!!
ERROR:

You never defined an element with id="count". Just check.
Also, when you define it, make sure it is a direct child of the body. You may try not to do this, but sometimes errors are caused.
Hope you understand now!

Related

Script in jquery to valide a form not work

I made a form to insert a new product on my site, and i want to validate it with js, but it don't work and i don't know why.
I have no errors in the console but nothing of the code work. I use the same code to validate a login form and it works so i don't know why here not working.
If you can help me to find the mistakes
Here is the js
$(document).ready(function(){
const form = $('#form');
const title = $('#title');
const descr = $('#descr');
const budget = $('#budget');
form.submit(e => {
if(!checkInputs()){
e.preventDefault();
}
});
});
function checkInputs() {
const titleValue = $.trim(username.value);
const descrValue = $.trim(descr.value);
const budgetValue = $.trim(budget.value);
console.log(titleValue);console.log(descrValue);console.log(budgetValue);
let status = false;
if(titleValue === '') {
status = setErrorFor(title, 'Inserisci un titolo');
}else{
status = setSuccessFor(title);
}
if(descrValue === '') {
status = setErrorFor(descr, 'Inserisci una descrizione');
}else {
status = setSuccessFor(descr);
}
if(budgetValue === '') {
status = setErrorFor(budget, 'Inserisci un budget');
} else {
status = setSuccessFor(budget);
}
/*
if(category === '') {
status = setErrorFor(budget, 'Seleziona una categoria');
}else{
status = setSuccessFor(budget);
}*/
return status;
}
function setErrorFor(input, message) {
const formControl = $(input).parent();
const small = $(formControl).find('small');
$(formControl).prop('classList', 'form-control error');
small.append(message);
return false;
}
function setSuccessFor(input) {
const formControl = $(input).parent();
$(formControl).prop('classList', 'form-control success');
return true;
}
here is the html (i know it's long sorry):
<form action = "projects/post_project.php" method ="post" id="form">
<div class="form-control">
<div class = "legend">Scegli un titolo per il tuo progetto</div>
<div><input type="text" name="title" id="title" placeholder = "es. Sito web per una piccola impresa" rows="5"></div>
<small></small>
</div>
<div class="form-control">
<div class = "legend">Dicci di più sul tuo progetto</div>
<div><textarea rows = "5" id = "descr" type="text" name="descr" placeholder = "Descrivi il tuo progetto"></textarea></div>
<small></small>
</div>
<div class="form-control">
<div class = "legend">Qual è il tuo budget?</div>
<select name="budget" id="budget">
<option>0€ - 250€</option>
<option>250€ - 750€</option>
<option>750€ - 1500€-</option>
<option>1500€ - 3000€</option>
<option>3000€ - 5000€</option>
<option>+ 5000€</option>
</select>
<small></small>
</div>
<!-- Pulsanti per scegliere la categoria -->
<div class = "legend">In che categoria inseriresti il tuo progetto? </div>
<small></small>
<div class = "category-list">
<input type = "radio" name = "category" value = "web" id = "radio1">
<label class = "category" for = 'radio1'>
<img class = "menu-icon" src = "img/web.png">
<span>Web</span>
</label>
<input type = "radio" name = "category" value = "app" id = "radio2">
<label class = "category" for = 'radio2'>
<img class = "menu-icon" src = "img/app.png">
<span>App</span>
</label>
<input type = "radio" name = "category" value = "database" id = "radio3">
<label class = "category" for = 'radio3'>
<img class = "menu-icon" src = "img/database.png">
<span>Database</span>
</label>
</div>
<div class = "category-list">
<input type = "radio" name = "category" value = "software" id = "radio4">
<label class = "category" for = 'radio4'>
<img class = "menu-icon" src = "img/software.png">
<span>Software</span>
</label>
<input type = "radio" name = "category" value = "sistemi" id = "radio5">
<label class = "category" for = 'radio5'>
<img class = "menu-icon" src = "img/sistemi.png">
<span>Sistemi</span>
</label>
<input type = "radio" name = "category" value = "altro" id = "radio6">
<label class = "category" for = 'radio6'>
<img class = "menu-icon" src = "img/other.png">
<span>Altro</span>
</label>
</div>
<!-- Fine pulsanti categoria -->
<div class = "btn"><input type="submit" value="Pubblica"></div>
</form>
here is the css:
.form-control.success input {
border-color: #2ecc71;
}
.form-control.error input {
border-color: #e74c3c;
}
.form-control small {
color: #e74c3c;
font-size: 11pt;
bottom: 0;
left: 0;
visibility: hidden;
}
.form-control.error small {
visibility: visible;
}
As mentioned in my comment, you define status as false and then use a number of IF statements to check for empty fields. As you perform each check, status gets updated to a new value. This means that regardless of the other checks, the last check is the only one that counts. With 3 checks it might be like:
status = false;
status = false;
status = true;
So the result would be true.
Consider the following code.
$(function() {
var form = $('#form');
var title = $('#title');
var descr = $('#descr');
var budget = $('#budget');
function checkInputs() {
var titleValue = title.val().trim();
var descrValue = descr.val().trim();
var budgetValue = budget.val().trim();
var status = true;
if (titleValue === '') {
status = status && setErrorFor(title, 'Inserisci un titolo');
} else {
status = status && setSuccessFor(title);
}
if (descrValue === '') {
status = status && setErrorFor(descr, 'Inserisci una descrizione');
} else {
status = status && setSuccessFor(descr);
}
if (budgetValue === '') {
status = status && setErrorFor(budget, 'Inserisci un budget');
} else {
status = status && setSuccessFor(budget);
}
console.log("Status", status);
return status;
}
function setErrorFor(input, message) {
var formControl = $(input).parent();
var small = $("small", formControl);
$(formControl).prop('classList', 'form-control error');
small.append(message);
return false;
}
function setSuccessFor(input) {
const formControl = $(input).parent();
$(formControl).prop('classList', 'form-control success');
return true;
}
form.submit(e => {
if (!checkInputs()) {
e.preventDefault();
}
});
});
.form-control.success input {
border-color: #2ecc71;
}
.form-control.error input {
border-color: #e74c3c;
}
.form-control small {
color: #e74c3c;
font-size: 11pt;
bottom: 0;
left: 0;
visibility: hidden;
}
.form-control.error small {
visibility: visible;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="projects/post_project.php" method="post" id="form">
<div class="form-control">
<div class="legend">Scegli un titolo per il tuo progetto</div>
<div><input type="text" name="title" id="title" placeholder="es. Sito web per una piccola impresa" rows="5"></div>
<small></small>
</div>
<div class="form-control">
<div class="legend">Dicci di più sul tuo progetto</div>
<div><textarea rows="5" id="descr" type="text" name="descr" placeholder="Descrivi il tuo progetto"></textarea></div>
<small></small>
</div>
<div class="form-control">
<div class="legend">Qual è il tuo budget?</div>
<select name="budget" id="budget">
<option>0€ - 250€</option>
<option>250€ - 750€</option>
<option>750€ - 1500€-</option>
<option>1500€ - 3000€</option>
<option>3000€ - 5000€</option>
<option>+ 5000€</option>
</select>
<small></small>
</div>
<!-- Pulsanti per scegliere la categoria -->
<div class="legend">In che categoria inseriresti il tuo progetto? </div>
<small></small>
<div class="category-list">
<input type="radio" name="category" value="web" id="radio1">
<label class="category" for='radio1'><img class = "menu-icon" src = "img/web.png"><span>Web</span></label>
<input type="radio" name="category" value="app" id="radio2">
<label class="category" for='radio2'><img class = "menu-icon" src = "img/app.png"><span>App</span></label>
<input type="radio" name="category" value="database" id="radio3">
<label class="category" for='radio3'><img class = "menu-icon" src = "img/database.png"><span>Database</span></label>
</div>
<div class="category-list">
<input type="radio" name="category" value="software" id="radio4">
<label class="category" for='radio4'><img class = "menu-icon" src = "img/software.png"> <span>Software</span></label>
<input type="radio" name="category" value="sistemi" id="radio5">
<label class="category" for='radio5'><img class = "menu-icon" src = "img/sistemi.png"><span>Sistemi</span></label>
<input type="radio" name="category" value="altro" id="radio6">
<label class="category" for='radio6'><img class = "menu-icon" src = "img/other.png"><span>Altro</span></label>
</div>
<!-- Fine pulsanti categoria -->
<div class="btn"><input type="submit" value="Pubblica"></div>
</form>
You might also consider performing the check on blur event so the User gets feedback as they move through the form.
$(function() {
var form = $('#form');
var errs = {
title: 'Inserisci un titolo',
descr: 'Inserisci una descrizione',
budget: 'Inserisci un budget',
};
function isEmpty(el) {
return $(el).val().length === 0;
}
function showError(el) {
var formControl = $(el).closest(".form-control");
formControl.removeClass("success").addClass("error");
$("small", formControl).html(errs[$(el).attr("id")]);
}
function hideError(el) {
var formControl = $(el).closest(".form-control");
formControl.removeClass("error").addClass("success");
$("small", formControl).html("");
}
$("#title, #descr, #budget").blur(function(e) {
var formControl = $(this).parent();
var id = $(this).attr("id");
if (isEmpty(this)) {
formControl.addClass("error");
showError(this);
} else {
formControl.addClass("success");
hideError(this);
}
});
});
.form-control.success input,
.form-control.success textarea,
.form-control.success select {
border-color: #2ecc71;
}
.form-control.error input,
.form-control.error textarea,
.form-control.error select {
border-color: #e74c3c;
}
.form-control small {
color: #e74c3c;
font-size: 11pt;
bottom: 0;
left: 0;
visibility: hidden;
}
.form-control.error small {
visibility: visible;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="projects/post_project.php" method="post" id="form">
<div class="form-control">
<div class="legend">Scegli un titolo per il tuo progetto</div>
<div>
<input type="text" name="title" id="title" placeholder="es. Sito web per una piccola impresa" rows="5">
</div>
<small></small>
</div>
<div class="form-control">
<div class="legend">Dicci di più sul tuo progetto</div>
<div>
<textarea rows="5" id="descr" type="text" name="descr" placeholder="Descrivi il tuo progetto"></textarea>
</div>
<small></small>
</div>
<div class="form-control">
<div class="legend">Qual è il tuo budget?</div>
<select name="budget" id="budget">
<option></option>
<option>0€ - 250€</option>
<option>250€ - 750€</option>
<option>750€ - 1500€-</option>
<option>1500€ - 3000€</option>
<option>3000€ - 5000€</option>
<option>+ 5000€</option>
</select>
<small></small>
</div>
<!-- Pulsanti per scegliere la categoria -->
<div class="legend">In che categoria inseriresti il tuo progetto? </div>
<small></small>
<div class="category-list">
<input type="radio" name="category" value="web" id="radio1">
<label class="category" for='radio1'><img class = "menu-icon" src = "img/web.png"><span>Web</span></label>
<input type="radio" name="category" value="app" id="radio2">
<label class="category" for='radio2'><img class = "menu-icon" src = "img/app.png"><span>App</span></label>
<input type="radio" name="category" value="database" id="radio3">
<label class="category" for='radio3'><img class = "menu-icon" src = "img/database.png"><span>Database</span></label>
</div>
<div class="category-list">
<input type="radio" name="category" value="software" id="radio4">
<label class="category" for='radio4'><img class = "menu-icon" src = "img/software.png"> <span>Software</span></label>
<input type="radio" name="category" value="sistemi" id="radio5">
<label class="category" for='radio5'><img class = "menu-icon" src = "img/sistemi.png"><span>Sistemi</span></label>
<input type="radio" name="category" value="altro" id="radio6">
<label class="category" for='radio6'><img class = "menu-icon" src = "img/other.png"><span>Altro</span></label>
</div>
<!-- Fine pulsanti categoria -->
<div class="btn"><input type="submit" value="Pubblica"></div>
</form>

document.getElementById in amp-script code giving element data differently

I am using AMP to develop my website. In that, I am using amp-script. When I use document.getElementById, it is giving the element data differently. I am looking for some properties like value etc. in it. But, can't those. See the below screenshot to look at the contents.
Please help me solve this.
Thank you...
EDIT: Added code snippet
HTML:
<form action="click" target="_blank" name="contact_form" id="contact_form" class="contact-form__block">
<div class="form__group">
<label for="message" class="form__label message_label">The idea that is brewing in your mind?
*</label>
<textarea name="message" id="form__textarea" class="form__textarea"></textarea>
</div>
<div class="form__group">
<label for="name" class="form__label name_label">Name </label>
<input type="text" name="name" id="form__name" class="form__input name" value="" autocomplete="off">
</div>
<div class="form__groups">
<div class="form__group">
<label for="phone" class="form__label phone_label">Phone Number </label>
<input type="text" name="phone" id="form__phone" class="form__input phone" value=""
autocomplete="off">
<!-- error message start -->
<!-- <div class="form__error e_mail">Please enter all required details.</div> -->
<!-- error message end -->
</div>
<div class="form__group">
<label for="mail" class="form__label email_label">Email *</label>
<input type="text" name="mail" id="form__mail" class="form__input mail">
</div>
</div>
<div class="form__group">
<div class="form-button__block">
<button type="button" name="submit" class="form__submit" id="form-submit">
<div class="arrow__btn-link-text">Let's Connect</div>
<amp-img src="stroke-arrow-right.svg" height="1" width="1"
alt="arrow right icon" class="arrow__btn-icon">
</button>
<!-- <div class="button--border"></div> -->
</div>
<div class="error_box">
<span class="error_message"></span>
</div>
</div>
</form>
JS:
var form = document.getElementById("form-submit"), msg;
form.addEventListener("click", function(event) {
event.preventDefault();
if (document.getElementById('form__textarea').value == '') {
msg = false;
} else {
msg = true;
}
if (document.getElementById('form__mail').value == '') {
email = false;
} else {
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var validEmail = emailReg.test(document.getElementById('form__mail').value);
if (!validEmail) {
email = false;
} else {
email = true;
}
}
if (document.getElementById('form__phone').value == '') {
phone = true;
document.getElementById('form__phone').value = "";
} else {
var phoneReg = /^([0-9]{10})|(\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})/;
var validPhone = phoneReg.test(document.getElementById('form__phone').value);
if (!validPhone) {
phone = false;
} else {
phone = true;
}
}
if (document.getElementById('form__name').value == '') {
document.getElementById('form__name').value = "";
} else {
name = true;
}
if (!msg || !email || !phone) {
console.log("Error in formmmmmmmmmmmmm");
return false;
} else {
console.log("valid formmmmmmmmmmmmmmmmmmmmmm");
}
});

Values in fields can not be recognized

why can not my function register a text that is clicked, but must I enter it manually to calculate in total?
Namely, my idea is that by clicking on a product, it is displayed in the input field [284] of the product price, and when clicking on a checkbox option to increase the price and display it at the end of [388], the text menu can now only it is compiled if I enter a number manually in field 285. How can I do it?
function displayAbo(el) {
document.getElementById("contactFormFieldId_284").value = el.querySelector('.product__title').textContent+ " " +el.querySelector('.product__price').textContent;
}
var checkBoxes = document.getElementsByClassName('contactFormClass_checkbox');
var sum = 0,
inputField = document.getElementById('contactFormFieldId_284'),
finalInput = document.getElementById('contactFormFieldId_388');
Array.prototype.slice.call(checkBoxes).forEach( (checkBox) => {
checkBox.addEventListener('change', calculateTotal, false);
})
inputField.addEventListener('blur', calculateSumWithInput, false);
function calculateTotal(e) {
if(e.target.checked) {
sum += parseInt(e.target.value, 10);
} else {
sum -= parseInt(e.target.value, 10);
}
finalInput.value ="CHF "+ sum + ".–";
}
function calculateSumWithInput(e) {
var re = /\d+/;
var value = re.exec(e.target.value);
if(value && !isNaN(value) && Number(value) === parseInt(value, 10)) {
sum = parseInt(value, 10);
finalInput.value = sum;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product__item" onclick="displayAbo(this)" id="product-medium" tabindex="-1" role="radio" aria-checked="false" aria-describedby="medium-desc">
<div class="product__inner" id="medium-desc">
<h3 class="product__title">LEUWIN M</h3>
<ul class="product__features">
<li class="product__features-item">40 Mbit/s</li>
<li class="product__features-item"><img src="themes/zuerich/images/I.png" style="width: 100px; margin-right: 110px;"></li>
</ul>
<h4 class="product__price">CHF 39.–</h4>
</div>
</div>
<div class="contact row">
<label for="contactFormFieldId_284" style="color: #003664; font-size: 16px; font-weight: bold;">[[284_LABEL]]</label>
<input class="contactFormClass_text" id="contactFormFieldId_284" type="text" name="contactFormField_284" value="[[284_VALUE]]" readonly />
</div>
<div class="contact row">
<label for="contactFormFieldId_385">[[385_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_385" type="checkbox" name="contactFormField_385" value="5" [[SELECTED_385]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_386">[[386_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_386" type="checkbox" name="contactFormField_386" value="15" [[SELECTED_386]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_387">[[387_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_387" type="checkbox" name="contactFormField_387" value="20" [[SELECTED_387]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_388" style="color: #003664; font-size: 16px; font-weight: bold;">[[388_LABEL]]</label>
<input class="contactFormClass_text" id="contactFormFieldId_388" type="text" name="contactFormField_388" value="0" />
</div>
I have made 2 changes.
Changed your blur function to click
inputField.addEventListener('click', calculateSumWithInput, false);
Added click triggers in your functions
inputField.click();
function displayAbo(el) {
document.getElementById("contactFormFieldId_284").value = el.querySelector('.product__title').textContent + " " + el.querySelector('.product__price').textContent;
inputField.click();
}
var checkBoxes = document.getElementsByClassName('contactFormClass_checkbox');
var sum = 0,
inputField = document.getElementById('contactFormFieldId_284'),
finalInput = document.getElementById('contactFormFieldId_388');
Array.prototype.slice.call(checkBoxes).forEach((checkBox) => {
checkBox.addEventListener('change', calculateTotal, false);
})
inputField.addEventListener('click', calculateSumWithInput, false);
inputField.click();
function calculateTotal(e) {
if (e.target.checked) {
sum += parseInt(e.target.value, 10);
} else {
sum -= parseInt(e.target.value, 10);
}
finalInput.value = "CHF " + sum + ".–";
}
function calculateSumWithInput(e) {
var re = /\d+/;
var value = re.exec(e.target.value);
if (value && !isNaN(value) && Number(value) === parseInt(value, 10)) {
sum = parseInt(value, 10);
finalInput.value = "CHF " + sum + ".–";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product__item" onclick="displayAbo(this)" id="product-medium" tabindex="-1" role="radio" aria-checked="false" aria-describedby="medium-desc">
<div class="product__inner" id="medium-desc">
<h3 class="product__title">LEUWIN M</h3>
<ul class="product__features">
<li class="product__features-item">40 Mbit/s</li>
<li class="product__features-item"><img src="themes/zuerich/images/I.png" style="width: 100px; margin-right: 110px;"></li>
</ul>
<h4 class="product__price">CHF 39.–</h4>
</div>
</div>
<div class="contact row">
<label for="contactFormFieldId_284" style="color: #003664; font-size: 16px; font-weight: bold;">[[284_LABEL]]</label>
<input class="contactFormClass_text" id="contactFormFieldId_284" type="text" name="contactFormField_284" value="[[284_VALUE]]" readonly />
</div>
<div class="contact row">
<label for="contactFormFieldId_385">[[385_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_385" type="checkbox" name="contactFormField_385" value="5" [[SELECTED_385]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_386">[[386_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_386" type="checkbox" name="contactFormField_386" value="15" [[SELECTED_386]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_387">[[387_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_387" type="checkbox" name="contactFormField_387" value="20" [[SELECTED_387]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_388" style="color: #003664; font-size: 16px; font-weight: bold;">[[388_LABEL]]</label>
<input class="contactFormClass_text" id="contactFormFieldId_388" type="text" name="contactFormField_388" value="0" />
</div>

Inserting values of checkbox back to form from local storage

I am getting two values of checkbox one is always false with type hidden. I created a local storage and where I stored value of checkbox. I want to put values back into my form from local storage. Can somebody please help me with that.
$(document).ready(function() {
InitalizeCache(GetKey());
});
function GetKey() {
var key = "local";
return key;
}
function CacheSpikeData() {
var form = $("#application-form").serializeArray();
CacheData(form, GetKey());
}
function InitalizeCache(key) {
window.onload = function() {
RecoverFormFromLocalStorage(key);
}
}
function RecoverFormFromLocalStorage(key) {
if (localStorage.getItem(key) !== null) {
var recover = confirm("You have some unsaved changes. Do you want to continue from where you left? ");
if (recover == true) {
RecoverFormFromLocalStorage2(key);
return true;
} else {
clearLocalStorage(key);
return false;
}
}
}
function ShowSpikeData() {
alert(localStorage.getItem(GetKey()));
}
function LoadSpikeData() {
RecoverFormFromLocalStorage2(GetKey());
}
function clearLocalStorage(key) {
localStorage.removeItem(key);
}
function CacheData(jsoNform, key) {
localStorage.setItem(key, JSON.stringify(jsoNform));
}
function RecoverFormFromLocalStorage2(key) {
var cache = localStorage.getItem(key);
var record = JSON.parse(localStorage.getItem(key));
if (cache !== null) {
$("#application-form *").filter(':input').each(function() {
if (this.type != "hidden") {
var cache = localStorage.getItem(key);
var record = JSON.parse(localStorage.getItem(key));
var cacheValue = $(record).find("Name=MyStringValue");
this.value = cacheValue;
alert(this.name + this.hidden);
}
});
}
}
<html><head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>View - NumberFormattingSample</title>
<link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.css">
<link rel="stylesheet" href="/css/site.css">
</head>
<body>
<div class="container body-content">
<h2>View</h2>
<form id="application-form" action="/Test/EditCheckbox" method="post" novalidate="novalidate">
<div class="form-horizontal">
<h4>TestClass</h4>
<hr>
<div class="form-group">
<label class="col-md-2 control-label" for="MyStringValue">MyStringValue</label>
<div class="col-md-10">
<input id="MyStringValue" name="MyStringValue" value="" aria-invalid="false" class="valid" type="text">
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="MyValue4">MyValue4</label>
<div class="col-md-10">
<div class="checkbox">
<input data-val="true" data-val-required="The MyValue4 field is required." id="MyValue4" name="MyValue4" value="true" type="checkbox">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="MyValue5">MyValue5</label>
<div class="col-md-10">
<div class="checkbox">
<input checked="checked" data-val="true" data-val-required="The MyValue5 field is required." id="MyValue5" name="MyValue5" value="true" type="checkbox">
</div>
</div>
</div>
<select>
<option>Option</option>
<option>Option1</option>
</select>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input value="Cache" type=button class="btn btn-default valid" onclick="CacheSpikeData()" aria-invalid="false">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input value="Show" type=button class="btn btn-default valid" onclick="ShowSpikeData()" aria-invalid="false">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input value="Load" type=button class="btn btn-default valid" onclick="LoadSpikeData()" aria-invalid="false">
</div>
</div>
</div>
<input name="__RequestVerificationToken" value="CfDJ8PubzbxcXzVMruNKDy4pjvN4hXQ65h4QOkv7uDsWo6fZ2L-XoEq_2ECU5X_vbG2E-06P5vqKof167EUuW9eWazRso-6D-lG8e74rUHikoOhsA_BVeWl4vx3OeutanaJtjbzs8RIpp4WuS74wbuf-5E0" type="hidden"><input name="MyValue4" value="false" type="hidden"><input name="MyValue5" value="false" type="hidden"></form>
<div>
Back to List
</div>
<hr>
<footer>
<p>© 2017 - NumberFormattingSample</p>
</footer>
</div>
<script src="/lib/jquery/dist/jquery.js"></script>
<script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="/js/site.js?v=EWaMeWsJBYWmL2g_KkgXZQ5nPe-a3Ichp0LEgzXczKo"></script>
<script src="/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
<script src="/js/Caching.js"></script>
</body></html>
I am simply trying to insert values back to form without deleting the hidden value of checkbox, but picking up the current value.
Try changing InitalizeCache to this
function InitalizeCache(key) {
RecoverFormFromLocalStorage(key);
}
Rename RecoverFormFromLocalStorage2 to populateDataFromLocalStorage and change to this
function populateDataFromLocalStorage(key) {
var cache = localStorage.getItem(key);
if (cache !== null) {
var formJson = JSON.parse(cache);
$("#application-form *").filter(':input').each(function() {
var name = $(this).attr('name');
var formRecord = formJson.find(function(record) {
return name === record.name;
}) || {};
if (this.type === "text") {
$(this).val(formRecord.value);
}
if (this.type === "checkbox") {
$(this).prop('checked', formRecord.value === 'true');
}
});
}
}
Update LoadSpikeData() to call the correct function name populateDataFromLocalStorage
Also the inputs at the end should have type="button"

How to perform on-submit form validation

I want to replace the after-submission checks in the form with on-the-fly completeness and correctness checks that are performed when a form field loses focus.
How can I do this?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE HTML>
<html>
<head>
<title>Form</title>
<style>
body {
width: 500px;
}
.part {
width: 100%;
padding: 5px;
border-bottom: 1px solid #000;
}
label {
margin-right: 5px;
}
.label-left {
text-align: right;
}
.label-right {
text-align: left;
}
.error {
color: #cc0000;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
//$(document).ready(function() {
function myValidateEMailAddress(email_address) {
var email_pattern = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return email_pattern.test(email_address);
}
function checkPassword(pwd_str) {
var my_pwd_pattern = /^(?=.*[a-zA-Z].*[a-zA-Z])(?=.*\d.*\d)[a-zA-Z0-9_]{6,20}$/;
return my_pwd_pattern.test(pwd_str);
}
function validatePhoneNumber(phone_number) {
var phone_pattern = /^(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]*$/;
return phone_pattern.test(phone_number);
}
$(document).ready(function() {
$('#form').submit(function(e) {
var my_errors = false;
$('.part> .error').remove();
$('#my_submission').empty();
$(':text, :password, textarea').each(function() {
$(this).val($.trim($(this).val()));
if ($(this).val() == '') {
$(this).parent().append('<div class="error">Please provide a value</div>');
my_errors = true;
}
});
if ($('#email').val() != '') {
if (!myValidateEMailAddress($('#email').val())) {
$('#email').parent().append('<div class="error">Please provide a correct e-mail address</div>');
my_errors = true;
}
}
if ($('#your_password').val() != '') {
if (!checkPassword($('#your_password').val())) {
$('#your_password').parent().append('<div class="error">Please provide a correct password.</div>');
my_errors = true;
}
}
if ($('#phone').val() != '') {
if (!validatePhoneNumber($('#phone').val())) {
$('#phone').parent().append('<div class="error">Please provide a correct phone number.</div>');
my_errors = true;
}
}
if ($('#addresses option:selected').val() == '') {
$('#addresses').parent().append('<div class="error">Please select one item</div>');
my_errors = true;
}
if ($(':radio[name="sex"]:checked').length == 0) {
$(':radio[name="sex"]:first').parent().after('<div class="error">Please select one item</div>');
my_errors = true;
}
if ($(':radio[name="subscription"]:checked').length == 0) {
$(':radio[name="subscription"]:first').parent().after('<div class="error">Please select one item</div>');
my_errors = true;
}
if ($('#likes option:selected').val() == '') {
$('#likes').parent().append('<div class="error">Please select one item</div>');
my_errors = true;
}
if (my_errors) {
return false;
}
else {
e.preventDefault();
var my_submission_array = $('#form').serialize().split('&');
if (my_submission_array.length > 0) {
$('#my_submission').html('<h2>Submitted Elements</h2><ul></ul>');
for (var i = 0; i < my_submission_array.length; i++) {
var my_pair = my_submission_array[i].split('=');
$('#my_submission > ul').append('<li>' + my_pair[0] + ': ' + my_pair[1] + '</li>\n');
}
}
}
});
});
// });
</script>
</head>
<body>
<h3>Output:</h3>
<h2>My Questionnaire</h2>
<form name="form" id="form" action="" method="post">
<div class="part">
<label for="addresses" class="label-left">How should you be addressed?</label>
<select name="addresses" id="addresses">
<option value="">Please select one</option>
<option value="first">Mr.</option>
<option value="second">Madam</option>
<option value="third">Miss</option>
<option value="fourth">Dr.</option>
<option value="fifth">Pr.</option>
</select>
</div>
<div class="part">
<fieldset>
<legend>Sex:</legend>
<input type="radio" name="sex" id="group1" value="1">
<label for="group1" class="label-right">Male</label>
<input type="radio" name="sex" id="group2" value="2">
<label for="group2" class="label-right">Female</label>
</fieldset>
</div>
<div class="part">
<label for="last_name" class="label-left">Last Name: </label>
<input type="text" name="last_name" id="last_name">
</div>
<div class="part">
<label for="first_name" class="label-left">First Name: </label>
<input type="text" name="first_name" id="first_name">
</div>
<div class="part">
<label for="email" class="label-left">E-Mail: </label>
<input type="text" name="email" id="email">
</div>
<div class="part">
<label for="your_password">Password:</label>
<input type="password" name="your_password" id="your_password" size="10" maxlength="20">
</div>
<div class="part">
<label for="phone" class="label-left">Phone number: </label>
<input type="text" name="phone" id="phone">
</div>
<div class="part">
<label for="likes" class="label-left">What are your likes?</label>
<select name="likes" id="likes">
<option value="">Please select one</option>
<option value="first">Programming</option>
<option value="second"> African literature</option>
<option value="third">Poetry</option>
<option value="four">Dancing</option>
</select>
</div>
<div class="part">
<fieldset>
<legend>Do you want to receive our newsletter ?</legend>
<input type="radio" name="subscription" id="group1" value="1">
<label for="group1" class="label-right">Yes</label>
<input type="radio" name="letter" id="group2" value="2">
<label for="group2" class="label-right">No</label>
</fieldset>
</div>
<div class="part">
<label for="comments" class="label-left">Write some comments below:</label>
<textarea name="comments" id="comments" cols="40" rows="3"></textarea>
</div>
<div class="part">
<input type="submit" name="submit" id="submit" value="Submit Form">
</div>
<div id="my_submission"></div>
</form>
</body>
</html>
Before I continue answering, I should note that you're putting jQuery script before <html> tag. This is incorrect. It has to be in <head>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
...
performed when a form field loses focus
An element loses focus when you click away from it. jQuery happends to have a blur event for this occasion:
$('input').on('blur', function() {
// your code here
});
So you might want to do it this way:
$('#email').on('blur', function() {
var emailVal = $(this).val();
if (!emailVal || !myValidateEMailAddress(emailVal)) {
$(this).parent().append('<div class="error">Please provide a correct e-mail address</div>');
my_errors = true;
}
});
the rest of the code might look similar.

Categories