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>
Related
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!
The files are in the the correct locations, both the form page and form complete page are in the same folder. When I click submit, it validates the form correctly, but if everything is entered correctly and validates, it does nothing, just takes away the asterisks like it's supposed to in the js. I want it to link to the form_complete.html page after you hit submit and the validation runs, but after it validates nothing happens,
The html:
<form id="contactform" action="form_complete.html" method="post">
<p class = "labelp">
<label for="name">Name: </label>
<input type="text" name="name" id="name" placeholder="Enter your name" >
<span>*</span><br><br>
</p>
<p class = "labelp">
<label for="age">Age: </label>
<input type="text" min="18" max="100" name="age" id="age" placeholder="Enter your age">
<!-- using type=text so I can practice isNaN in js -->
<span>*</span><br><br>
</p>
<p class = "labelp"></p>
<label for="country">Country: </label>
<select name="country" id="country">
<option value ="">Select a country</option>
<option>USA</option>
<option>Canada</option>
<option>Mexico</option>
<option>Brazil</option>
<option>Japan</option>
<option>China</option>
<option>Other</option>
</select>
<span>*</span><br><br>
</p>
<p class = "labelp">
<label for="email">E-mail: </label>
<input type="email" name="email" id="email" placeholder="Enter your E-mail">
<span>*</span><br><br>
</p>
<p class = "labelp">
<label for="bday">Birthday: </label>
<input type="date" name="bday" id="bday">
<span>*</span><br><br>
</p>
<p class = "labelp">
<label for="gender" id="gender">Gender: </label>
<input type="radio" name="gender" value="male" id="male"> Male
<input type="radio" name="gender" value="female" id="female"> Female
<input type="radio" name="gender" value="other" id="other"> Other
<br><br>
</p>
<label>Comments: </label>
<textarea rows="5" cols="30"> </textarea><br><br>
<input type="button" id="registerbtn" value="Submit">
<input type="button" id="resetbtn" value="Reset">
</form>
The javascript:
"use strict";
var $ = function(id) { return document.getElementById(id);};
var processEntries = function(){
var isValid = true;
// values
var name = $("name").value;
var age = $("age").value;
var country = $("country").value;
var email = $("email").value;
var bday = $("bday").value;
var gender = "";
if ($("male").checked){gender = "Male";}
if ($("female").checked){gender = "Female";}
if ($("other").checked){gender = "Other";}
console.log(gender); //check if gender buttons work
// name
if(name == ""){
$("name").nextElementSibling.firstChild.nodeValue = "This field is required!";
isValid = false;}
else{
$("name").nextElementSibling.firstChild.nodeValue = "";
}
// age
if(age == ""){
$("age").nextElementSibling.firstChild.nodeValue = "This field is required!";
isValid = false;
}
else if(isNaN(age)){
$("age").nextElementSibling.firstChild.nodeValue = "This field must be a number!";
isValid = false;
}
else{
$("age").nextElementSibling.firstChild.nodeValue = "";
}
//country
if(country == ""){
$("country").nextElementSibling.firstChild.nodeValue = "Please select a country!";
isValid = false;}
else{
$("country").nextElementSibling.firstChild.nodeValue = "";
}
//email
if(email == ""){
$("email").nextElementSibling.firstChild.nodeValue = "This field is required!";
isValid = false;}
else{
$("email").nextElementSibling.firstChild.nodeValue = "";
}
//birthday
if(bday == ""){
$("bday").nextElementSibling.firstChild.nodeValue = "This field is required!";
isValid = false;}
else{
$("bday").nextElementSibling.firstChild.nodeValue = "";
}
}
var resetForm = function(){
$("contactform").reset();
$("name").nextElementSibling.firstChild.nodeValue = "*";
$("age").nextElementSibling.firstChild.nodeValue = "*";
$("country").nextElementSibling.firstChild.nodeValue = "*";
$("email").nextElementSibling.firstChild.nodeValue = "*";
$("bday").nextElementSibling.firstChild.nodeValue = "*";
}
window.onload = function() {
$("registerbtn").onclick = processEntries;
$("resetbtn").onclick = resetForm;
$("name").focus();
}
Please put below condition at the end of "processEntries" function
if(isValid){
$("#contactform").submit();
}
So for the past few days I've been struggling on how to pas information from my product page to an order form. I'm to the point where I can't figure out what to do with the coding that I've done to make the web pages.
This is all of my coding for three pages
Home page:
body{
background-color:#56A5EC;
}
div.banner{
text-align:center;
color:#ED9C55;
font-size:45px;
width:750px;
height:50px;
position:relative;
top:0px;
margin-left:auto;
margin-right:auto;
border:1px solid black;
}
div.nav{
font-size:25px;
color:#56A5EC;
background-color:#ED9C55;
width:750px;
height:30px;
margin-left:auto;
margin-right:auto;
position:relative;
top:3px;
border:1px solid black;
}
div.main{
position:relative;
top:6px;
width:750px;
height:600px;
margin-left:auto;
margin-right:auto;
position:relative;
border:1px solid black;
background-color:white;
}
div.footer{
background-color:#ED9C55;
font-size: 20px;
height:180px;
width:752px;
margin-left:auto;
margin-right:auto;
position:relative;
bottom:8px;
z-index:1;
color:white;
}
p.welcome{
text-align:center;
margin-left:auto;
margin-right:auto;
font-size:25px;
color:blac
<div class="wrapper">
<div class="banner">Welcome to Electro-Market</div>
<div class="nav">Product page</div>
<div class=""main>
<p class="welcome">
Welcome to my store where we sell electronic devices that you may enjoy. Here we are committed to satisfying your needs.
</p>
</div>
<div class="footer">
If you need to contact about stock avaliablity please don't hesitate to call (918)999-0987.
</div>
</div>
Product page:
var products = [];
var url_string = document.location.search.substring(1,document.location.search.length);
if( url_string.length > 0 ) {
var parameters = url_string.split('&');
for(var x = 0 ; x < parameters.length ; x++ ) {
products.push(parameters[x].split('='));
}
console.log(products);
} else {
console.log("no parameters");
}
window.onload = function( ) {
var form = document.getElementById("order_form");
form.onsubmit = function( ) {
var controls = document.getElementsByTagName("input");
for( var x = 0 ; x < controls.length ; x++ ){
if( controls[x].type == "checkbox" && controls[x].checked ) {
return true;
}
}
alert("You must select one product at least");
return false;
}
}
body{
background-color:#56A5EC;
}
<form action="lab07_order_form.html" method="get" id="order_form">
<h2>Lenovo Computer - $650.00</h2>
<div>
<input type="checkbox" name="Product1" value="" id="Product1"/>
<label for="product-1"><img src="Lenovo-pc.jpg" alt="Computer" style="width:225px;height:200px;"> Thi computer has many features built into it such as Intel i5 core processor 8GB ram and 1 TB of memory.</label>
</div>
<h2>Nintendo 64 - $50.00</h2>
<div>
<input type="checkbox" name="Product2" value="" id="Product2"/>
<label for="product-2"><img src="Nintendo-64.jpg" alt="Nintendo" style="width:225px;height:200px;"> A console from the 90's that many kids loved to play at a friends house and an all around family activity. Though cartridges are sold separately and come in serveral different games.</label>
</div>
<h2>Playstation 2 - $150.00</h2>
<div>
<input type="checkbox" name="Product3" value="" id="Product3"/>
<label for="product-3"><img src="playstation.jpg" alt="ps2" style="width:225px;height:200px;"> The Playstation 2 is a more modern console that is one of our highly anticipated consoles.</label>
</div>
<h2>Xbox - $125.00</h2>
<div>
<input type="checkbox" name="Product4" value="" id="Product4"/>
<label for="product-4"><img src="xbox.jpg" alt="xbox" style="width:225px;height:200px;">Xbox is made by microsoft and has one of the most iconic games ever played Halo and are in limited supply</label>
</div>
<div>
<input type="submit" value="Purchase item's"/>
</div>
</form>
<form action="lab_07.html" method="get" id="lab_07">
<input type="submit" value="Back"/>
</form>
Form page:
var ids = ['first_name', 'last_name','street_address','city','state','zip', 'Billing_address', 'Billing_city', 'Billing_state', 'Billing_zip', 'Card_type', 'Card_number', 'Card_date'];
function validate( ){
var errors = new Array();
for(var x = 0 ; x <document.forms[0].elements.length ; x++ ) {
if(document.forms[0].elements[ x ].type == "text"){
if(document.forms[0].elements[ x ].value == ""){
errors.push("The " + document.forms[0].elements[x].name + " field cannot be blank\n");
document.forms[0].elements[x].className = "in_error";
} else {
document.forms[0].elements[x].className = "no_error";
}
}
if( document.forms[0].elements[x].type == "select-one"){
if(document.forms[0].elements[x].selectIndex == 0){
errors.push("The " + document.forms[0].elements[x].name + " field cannot be blank\n");
document.forms[0].elements[x].className = "in_error";
} else {
document.forms[0].elements[x].className = "no_error";
}
}
}
if(errors.length == 0 ){
return true;
} else {
clear_errors( );
show_errors( errors );
return false;
}
}
var products = [];
var url_string = document.location.search.substring(1,document.location.search.length);
if( url_string.length > 0 ) {
var parameters = url_string.split('&');
for(var x = 0 ; x < parameters.length ; x++ ) {
products.push(parameters[x].split('='));
}
console.log(products);
} else {
console.log("no parameters");
}
function FillBilling(z){
if(z.billingtoo.checked == true) {
z.Billing_address.value = z.street_address.value;
z.Billing_city.value = z.city.value;
z.Billing_state.value = z.state.value;
z.Billing_zip.value = z.zip.value;
}
if(z.billingtoo.checked == false){
z.Billing_address.value = '';
z.Billing_city.value = '';
z.Billing_state.value = '';
z.Billing_zip.value = '';
}
}
function clear_errors(){
var div = document.getElementById( "errors" );
while(div.hasChildNodes()){
div.removeChild(div.firstChild);
}
}
function show_errors( errors ) {
var div = document.getElementById( "errors" );
for( var x = 0 ; x < errors.length ; x++ ) {
var error = document.createTextNode( errors[ x ]);
var p = document.createElement( "p" );
p.appendChild(error);
div.appendChild(p);
}
}
window.onload = function() {
document.forms[ 0 ].onsubmit = validate;
for( var x = 0 ; x < ids.length ; x++ ) {
var element = document.getElementById(ids[x]);
element.onfocus = function(){
console.log(this.id + " has been focused");
this.className = "element_focused";
document.getElementById(this.id + "_label").className = "element_focused";
}
element.onblur = function( ) {
console.log(this.id + " has been blurred");
this.className = "";
document.getElementById(this.id + "_label").className = "";
}
}
var products_div = document.getElementById("products");
var order_form = document.getElementById("order_form");
for( var x = 0 ; x < products.length ; x++ ) {
//create colored background div's
var div = document.createElement("div");
div.style.backgroundColor = products[x][1];
products_div.appendChild(div);
//create form fields
var input = document.createElement("input");
input.type = "hidden";
input.name = products[x][0];
input.value = products[x][1];
order_form.appendChild(input);
}
}
#errors {
color: #F00;
}
.in_error{
background-color: #F00;
}
.no_error{
background-color: #FFFFFF;
}
input.element_focused, select.element_focused {
border: 5px solid #F00;
}
label.element_focused {
color: #F00;
}
<h1>Products</h1>
<div id="products"></div>
<div id="errors"></div>
<form method="get" action="https://suchnull.com/examples/echo">
<p>
<label for="first_name" id="first_name_label">First Name:</label>
<input type="text" name="first name" value="" id="first_name"/>
</p>
<p>
<label for="last_name" id="last_name_label">Last Name:</label>
<input type="text" name="last name" value="" id="last_name"/>
</p>
<p>
<label for="street_address" id="street_address_label">Shipping Address:</label>
<input type="text" name="street address" value="" id="street_address"/>
<input type="checkbox" onclick="FillBilling(this.form)" name="billingtoo"/>
</p>
<p>
<label for="city" id="city_label">Shipping City:</label>
<input type="text" name="city" value="" id="city"/>
</p>
<p>
<label for="state" id="state_label">Shipping State:</label>
<input type="text" name="state" value="" id="state"/>
</p>
<p>
<label for="zip" id="zip_label">Shipping Zip:</label>
<input type="text" name="zip" value="" id="zip"/>
</p>
<p>
<label for="Billing_address" id="Billing_address_label">Billing address:</label>
<input type="text" name="Billing address" value="" id="Billing_address"/>
</p>
<p>
<label for="Billing_city" id="Billing_city_label">Billing City:</label>
<input type="text" name="Billing city" value="" id="Billing_city"/>
</p>
<p>
<label for="Billing_state" id="Billing_state_label">Billing State:</label>
<input type="text" name="Billing state" value="" id="Billing_state"/>
</p>
<p>
<label for="Billing_zip" id="Billing_zip_label">Billing Zip:</label>
<input type="text" name="Billing zip" value="" id="Billing_zip"/>
</p>
<p>
<label for="Card_type" id="Card_type_label">Credit Card Type:</label>
<input type="text" name="Card type" value="" id="Card_type"/>
</p>
<p>
<label for="Card_number" id="Card_number_label">Credit Card Number:</label>
<input type="text" name="Card number" value="" id="Card_number"/>
</p>
<p>
<label for="Card_date" id="Card_date_label">Credit Card Expiration Date:</label>
<input type="text" name="Card date" value="" id="Card_date"/>
</p>
<p>
<form method="get" action="https://suchnull.com/examples/echo">
<input type="checkbox" name="checkbox" value="check" /> I've completed the information
<input type="submit" name="submit" value="submit" onclick="if(!this.form.checkbox.checked){alert('You must agree to the terms first.');return false}" />
</form>
</p>
</form>
Can anyone tell me what I'm doing wrong and help me understand how to transfer the image of the product, price, and name because I'm completely lost on how to do this.
So what I am trying to do here is when the submit button is clicked pull all of the values from the textboxes and display them in a p tag that I have on my html page. I have been tring to figure this out for days. Can somebody let me know what I am doing wrong?
/* JavaScript */
$("#submit").click(function(){
var doc = $("#doctorate").val()
var Name = $("#first_name").val();
var Last = $("#last_name").val();
var T = Doc + " "+ Name + " " + Last
break
var Certs = $("#certs").val()
break
var Title = $("#title").val()
break
var Department = $("#department").val()
break
var Numb = $("#number").val()
break
var Web = $("#website").val()
break
var Ema = $("#email").val()
document.getElementById('output').innerHTML = T;
})
HTML unchanged
The big problem I see is that you keep assigning the same thing to your output. Try something like this (reduced for brevity):
function myOut() {
var output = document.getElementById("certs").value;
output = output + document.getElementById("title").value;
if (certs != null) {
document.getElementById("output").innerHTML = output;
}
}
<input type="text" id="certs" />
<input type="text" id="title" />
<p id="output"></p>
<button onclick="myOut()">
Sub
</button>
Here you can try this one.
var role = document.getElementById("role").value;
var first_name = document.getElementById("first_name").value;
var last_name = document.getElementById("last_name").value;
var doctorate = document.getElementById("doctorate").value;
var certs = document.getElementById("certs").value;
var title = document.getElementById("title").value;
var department = document.getElementById("department").value;
var number = document.getElementById("number").value;
var website = document.getElementById("website").value;
var email = document.getElementById("email").value;
var output = document.getElementById("output").value;
$("#submit").click(function(){
var N = $("#first_name").val();
var L = $("#last_name").val();
var T = N + " " + L;
if (doctorate.checked) {
document.getElementById('output').innerHTML = T;
}
if (first_name != null) {
document.getElementById('output').innerHTML = T;
}
if (last_name != null) {
document.getElementById('output').innerHTML = T;
}
if (certs != null) {
document.getElementById('output').innerHTML = T;
}
if (title != null) {
document.getElementById('output').innerHTML = T;
}
if (department != null) {
document.getElementById('output').innerHTML = T;
}
if (number != null) {
document.getElementById('output').innerHTML = T;
}
if (website != null) {
document.getElementById('output').innerHTML = T;
}
if (email != null) {
document.getElementById('output').innerHTML = T;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset id="role">
<legend>My Role</legend>
<label for="faculty">
<input type="radio" name="role" id="faculty" value="faculty" />
Faculty
</label>
<label for="staff">
<input type="radio" name="role" id="staff" value="staff" />
Staff
</label>
</fieldset>
<fieldset id="userinformation">
<legend>User Information</legend>
<label for="doctorate">
Doctorate?
<input type ="checkbox" id="doctorate" value="" />
</label>
<label>
First Name:
<input type="text" name="name" id="first_name" required />
</label>
<label>
Last Name:
<input type="text" name="name" id="last_name" required />
</label>
<label>
Certifications:
<input type="text" name="cert" id="certs" />
</label>
<label>
Title:
<input type="text" name="title" id="title" required />
</label>
<label>
Department:
<select id="department" required>
<option disabled selected value>-Select a Department-</option>
<option>School of Information Technology</option>
<option>Mathematics</option>
<option>English</option>
<option>History</option>
<option>Natural Sciences</option>
<option>Psychology</option>
<option>School of Health Sciences</option>
</select>
</label>
<label>
Primary Phone #:
<input type="tel" name="number" id="number" placeholder="444-123-1234" pattern="^\d{3}-\d{3}-\d{4}$"/>
</label>
<label>
Email:
<input type="email" name="email" id="email" placeholder="JDoe#example.com" required />
<span id="err3"></span>
</label>
<label>
Website:
<input type="text" name="website" id="website" placeholder="http//:www.example" pattern="https?://.+" />
</label>
</fieldset>
<fieldset id = "results">
<p id="output"></p>
</fieldset>
<fieldset id="submit_button">
<input type="button" id="submit" value="submit" />
</fieldset>
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.