I am trying to get the push notices visible upon pressing the button, depending on your age either of the "You are of legal age" or "You are not of legal age" messages should be written out depending on the age input by the user, if all previous inputs are filled and password is correct.
let nameElement = document.getElementById("UNameInput");
let faultElement = document.getElementById("errorOutput");
let ageElement = document.getElementById("AgeInput");
let clickElement = document.getElementById("button");
let passwordElement = document.getElementById("PasswordInput");
clickElement.addEventListener("click", function (e) {
let feedback = [];
let users = [];
if (UNameInput.value === '' || UNameInput.value === null) {
feedback.push('Name input missing')
}
else if (AgeInput.value === '' || AgeInput.value === null) {
feedback.push('Age input missing')
}
else if (PasswordInput.value !== 'IHM') {
feedback.push('Password is not valid')
} else feedback.forEach((item, i) => {
if (ageElement.value < 18) {
feedback.push ("You are not of legal age")
}
else {
feedback.push("You are of legal age")
}
});
if (feedback.length > 0) {
e.preventDefault()
faultElement.innerText = feedback.join(", ")
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inlämningsuppgift</title>
<script src="JSny copy.js" defer></script>
</head>
<body>
<div id="errorOutput"></div>
<p id="output"></p>
<div>
<label for="UNameInput">Name Input</label>
<input id="UNameInput" name="name" type="text">
</div>
<div>
<label for="AgeInput">Age Input</label>
<input id="AgeInput" name="age" type="number">
</div>
<div>
<label for="PasswordInput">Password Input</label>
<input id="PasswordInput" name="password" type="password">
</div>
<button id="button">Submit</button>
</body>
</html>
Updated jsfiddle: (Added name and age input to push message along with the legal notifcation)
jsfiddle
You need to put AgeInput.value !== '' at the end of if else condition. Also, I remove the iteration of the feedback.push()
else if(AgeInput.value !== ''){
if (ageElement.value < 18) {
feedback.push ("You are not of legal age")
}else {
feedback.push("You are of legal age")
}
}
Why are you iterating feedback in your else statement?
When feedback array is empty (and it is when your code enters else statement) there is nothing that it can iterate over so it doesn't check if (ageElement.value < 18) hence no output.
const nameElement = document.getElementById("UNameInput");
const ageElement = document.getElementById("AgeInput");
const passwordElement = document.getElementById("PasswordInput");
const faultElement = document.getElementById("errorOutput");
const clickElement = document.getElementById("button");
clickElement.addEventListener("click", function (e) {
const feedback = [];
if (nameElement.value === '' || nameElement.value === null) {
feedback.push('Name input missing');
} else if (ageElement.value === '' || ageElement.value === null) {
feedback.push('Age input missing');
} else if (passwordElement.value !== 'IHM') {
feedback.push('Password is not valid');
} else {
if (ageElement.value < 18) {
feedback.push("You are not of legal age");
} else {
feedback.push("You are of legal age");
}
}
if (feedback.length > 0) {
e.preventDefault();
faultElement.innerText = feedback.join(", ");
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inlämningsuppgift</title>
</head>
<body>
<div id="errorOutput"></div>
<p id="output"></p>
<div>
<label for="UNameInput">Name Input</label>
<input id="UNameInput" name="name" type="text">
</div>
<div>
<label for="AgeInput">Age Input</label>
<input id="AgeInput" name="age" type="number">
</div>
<div>
<label for="PasswordInput">Password Input</label>
<input id="PasswordInput" name="password" type="password">
</div>
<button id="button">Submit</button>
</body>
</html>
Related
// Staff name validation:
function staffValidation () {
var valid = true;
var staff_name = document.getElementById("staff_name").value;
var validname = /^[a-zA-Z\s]*$/;
error1 = document.getElementById("errorMsg1").innerHTML ="*";
if (staff_name == "" ) {
document.getElementById("errorMsg1").innerHTML = "*STaff name is required";
valid = false;
}
else if (full_name.match(validname)) {
valid= true;
}
else {
document.getElementById("errorMsg1").innerHTML = "* Only letters and white spaces allowed";
valid= false;
}
return valid;
}
//email validation:
function emailValidation () {
var valid = true;
var validEmail = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var email = document.getElementById("email1").value;
error2 = document.getElementById("errorMsg2").innerHTML ="*";
if (email == "" ) {
document.getElementById("errorMsg2").innerHTML = "*Email is required";
valid = false;
}
else if (email.match(validEmail)) {
valid = true;
}
else {
document.getElementById("errorMsg2").innerHTML = "*Please enter a valid email.";
valid =false ;
}
return valid;
}
// Subject validation:
function subjectValidation () {
var valid = true;
var subject = document.getElementById("subject1").value;
var validname = /^[a-zA-Z\s]*$/;
error3 = document.getElementById("errorMsg3").innerHTML ="*";
if (staff_name == "" ) {
document.getElementById("errorMsg3").innerHTML = "*Subject is required";
valid = false;
}
else if (subject.match(validname)) {
valid= true;
}
else {
document.getElementById("errorMsg3").innerHTML = "* Only letters and white spaces allowed";
valid= false;
}
return valid;
}
// Problem type validation:
function problemValidation () {
var valid = true;
var prob = document.getElementsByName("problem_type")[0].value;
error4 = document.getElementById("errorMsg4").innerHTML ="*";
if (prob == "") {
document.getElementById("errorMsg4").innerHTML = "*Please select a problem type.";
valid = false;
}
else {
valid = true;
}
return valid;
}
// Description validation:
function descriptionValidation () {
var valid = true;
var description = document.getElementById("description1").value;
error5 = document.getElementById("errorMsg5").innerHTML ="*";
if (description == "" ) {
document.getElementById("errorMsg5").innerHTML = "*Description is required";
valid = false;
}
else if (description.length < 100) {
document.getElementById("errorMsg5").innerHTML = "*Please be more specific, type 100 characters minimum.";
valid = false;
}
return valid;
}
// function for form submission:
function formSubmit () {
if ( staffValidation() == false || emailValidation() == false || subjectValidation() == false || problemValidation() == false || descriptionValidation() == false ) {
document.getElementById("errorMsg").innerHTML = "* Please complete the required fields correctly";
return false;
}
else {
return true;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="log-it-reports2.css">
<script src="log-it-reports.js"></script>
<title>WearView Academy Homepage</title>
</head>
<body>
<div class= "content">
<div class="inner-body">
<div class="form1">
<form method="GET" onsubmit=" return formSubmit() " action="#">
<div class="error1" id= "errorMsg"></div>
<div class="error" id= "errorMsg1"></div>
<div>
<label for="staff_name"><b>Staff Name:</b></label>
<input class="field" name="staff_name" onclick=" return staffValidation()" onchange=" return staffValidation()" id="subject" type="text" placeholder="Staff Name" >
</div><br>
<div class="error" id= "errorMsg2"></div>
<div>
<label for="email"><b>Email:</b></label>
<input class="field" id="email1" name="email" onclick=" return emailValidation()" onchange=" return emailValidation()" type="email" placeholder="staff#wearview.com">
</div><br>
<div class="error" id= "errorMsg3"></div>
<div>
<label for="subject"><b>Subject:</b></label>
<input class="field" name="subject" id="subject" onclick=" return subjectValidation()" onchange=" return subjectValidation()" type="text" placeholder="Subject Title" >
</div><br>
<div class="error" id= "errorMsg4"></div>
<div>
<select onclick=" return problemValidation()" onchange=" return problemValidation()" class="field4" name="problem_type" id="problemtypes">
<option value="">Problem Type</option>
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
<option value="Software&Hardware">Software & Hardware</option>
<option value="Other">Other</option>
</select>
</div><br>
<div class="error" id= "errorMsg5"></div>
<div>
<textarea class="field2" id="description1" name="description" onclick=" return descriptionValidation()" onchange=" return descriptionValidation()" placeholder="Description goes here" name="descript" rows="15" cols="90"></textarea>
</div>
<div>
<button class="field3" type="submit" class="btn">Submit</button>
<input type="checkbox" id="notify" name="notify" value="">
<label for="notify">Inform me by email when issue is resolved.</label>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
Im trying to validate a form using javascript code, however the form action automatically takes place without any validation happening. i would like to know why my javascript code is not being called which i sourced in the head tag with the name "log-it-issues.js", could it be a syntax error ? i tried to scan my code for such an error , but no result, thank you for taking time to look at my code.
The input stuff id isn't set
Give that input an id and the form will work correctly : staff_name
<input class="field" name="staff_name" id="staff_name" onclick=" return staffValidation()" onchange=" return staffValidation()" id="subject" type="text" placeholder="Staff Name">
Hi everyone i have question about my code the plan was that the script was supposed to display message if someone did not enter anything in input or enter somethink thats did not match to my pattern (but if someone lift message will disappear [this doesnt work]) and i dont know where is problem and how to fix it
here is my code:
html
<html lang="pl">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="odp.php" method="post" id="form">
<div>
<label for="imie">Imie</label>
<input type="text" name="imie" id="imie" placeholder="Imie" required>
<span></span>
</div>
<div>
<label for="nazwisko">Nazwisko</label>
<input type="text" name="nazwisko" id="nazwisko" placeholder="Nazwisko" required>
<span></span>
</div>
<div>
<label for="pesel">Pesel</label>
<input type="number" placeholder="pesel" name="pesel" id="pesel" required>
<span></span>
</div><br>
adres zamieszkania:
<div>
<label for="kod">kod</label>
<input type="text" name="kod" id="kod" placeholder="kod" required>
<span></span>
</div>
<div>
<label for="miejscowosc">miejscowość</label>
<input type="text" name="miejscowosc" id="miejscowosc" placeholder="Miejscowość" required>
<span></span>
</div>
<div>
<label for="ulica">ulica</label>
<input type="text" name="ulica" id="ulica" placeholder="Ulica" required>
<span></span>
</div>
<div>
<label for="nrdomu">nr domu</label>
<input type="text" name="nrdomu" id="nrdomu" placeholder="nr domu" required>
<span></span>
</div>
<div>
<label for="nrmieszkania">nr mieszkania</label>
<input type="text" name="nrmieszkania" id="nrmieszkania" placeholder="nr mieszkania">
<span></span>
</div><br>
<div>
<label for="emial">Emial</label>
<input type="email" name="email" placeholder="email" id="email" required>
<span></span>
</div>
<div>
<label for="number">Numer Telefonu</label>
<input type="number" name="nrtel" placeholder="Numer-telefonu" id="number" required>
<span></span>
</div>
<input type="submit" id="submit">
</form>
<script src="main.js"></script>
</body>
</html>
and my js
let nazwisko = document.getElementById('nazwisko');
let pesel = document.getElementById('pesel');
let kod = document.getElementById('kod');
let miejscowosc = document.getElementById('miejscowosc');
let ulica = document.getElementById('ulica');
let nrdomu = document.getElementById('nrdomu');
let nrmieszkania = document.getElementById('nrmieszkania');
let email = document.getElementById('email');
let number = document.getElementById('number');
let span = document.getElementsByTagName('span');
let form = document.getElementById('form');
var arr = [imie,nazwisko,pesel,kod,miejscowosc,ulica,nrdomu,nrmieszkania,email,number];
for(let i = 0; i < arr.length; ++i){
var regex;
console.log(arr[i]);
if(i == 0 || i == 1 || i == 4 || i == 5){
regex = /^[A-Za-zĄĘĆŁŃÓŚŻŹąęćłńóśżź]{3,100}$|^[A-Za-zĄĘĆŁŃÓŚŻŹąęćłńóśżź]+[A-Za-zĄĘĆŁŃÓŚŻŹąęćłńóśżź0-9\s\-]+[A-Za-zĄĘĆŁŃÓŚŻŹąęćłńóśżź0-9]{1,100}$/;
console.log(arr[i].value.match(regex));
}
if(i == 2){
regex = /^[0-9]{11}$/;
console.log(regex);
}
if(i == 3){
regex = /^[0-9]{2}-[0-9]{3}$/i;
console.log(regex);
}
if(i == 6){
regex = /[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|1000/i;
console.log(regex);
}
if(i == 7){
regex = /[0-9]/gm;
console.log(regex);
}
if(i == 8){
regex = /\b[\w\.-]+#[\w\.-]+\.\w{2,4}\b/gi;
console.log(regex);
}
if(i == 9){
regex = /^(?:\+\d\d)?\d{3}(-?)\d{3}\1\d(\d\d)?$/gm;
console.log(regex);
}
arr[i].onblur = function(){
if(arr[i].value.match(regex)){
span[i].innerHTML = "";
}else{
span[i].innerHTML = "Uzupełnij " + arr[i].name;
span[i].style.color = 'red';
}
}
if(i == 7){
arr[i].onblur = span[i].innerHTML = "";
}
}```
the <span></span> tags you are using in the Html do not have an id to which your logic can set the value that you define in the JS
else{
span[i].innerHTML = "Uzupełnij " + arr[i].name;
span[i].style.color = 'red';
}
I'm trying to get the user inputs to be pushed out as a message into a <div> via the button press after confirming that all the inputs are filled and the correct password has been entered. That part works fine but my forEach is not working:
If the user has input a number value lower than 18, I want an if that types out via push "Your name is UName and you are Age years old, you are not of legal age", or else the same result as above but ending with "...you are of legal age".
Any idea how I should go forth?
let nameElement = document.getElementById("UNameInput");
let faultElement = document.getElementById("errorOutput");
let ageElement = document.getElementById("AgeInput");
let clickElement = document.getElementById("button");
let passwordElement = document.getElementById("PasswordInput");
clickElement.addEventListener("click", function(e) {
let feedback = [];
if (UNameInput.value === '' || UNameInput.value === null) {
feedback.push('Name input missing')
}
if (AgeInput.value === '' || AgeInput.value === null) {
feedback.push('Age input missing')
} else if (PasswordInput.value !== 'IHM') {
feedback.push('Password is not valid')
} else {
feedback.forEach((item, i) => {
if (item.AgeInput < 18) {
feedback.push("You are not of not legal age")
} else {
feedback.push(" You are of legal age ")
}
});
}
if (feedback.length > 0) {
e.preventDefault()
faultElement.innerText = feedback.join(", ")
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="JSny.js" defer></script>
</head>
<body>
<div id="errorOutput"></div>
<p id="output"></p>
<div>
<label for="UNameInput">Name Input</label>
<input id="UNameInput" name="name" type="text">
</div>
<div>
<label for="AgeInput">Age Input</label>
<input id="AgeInput" name="age" type="number">
</div>
<div>
<label for="PasswordInput">Password Input</label>
<input id="PasswordInput" name="password" type="password">
</div>
<button id="button">Submit</button>
</body>
</html>
You are using AgeInput instead of ageElement in the if statement.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>To Do List</h1>
<form>
<input autocomplete="off" autofocus id="todotext"
type="text">
<input onclick="serve(); return false" type="submit">
</form>
<ol id="add"></ol>
</body>
<script>
function serve(){
const neww = document.getElementById('add');
let text = document.getElementById('todotext').value;
const a = document.createElement('li');
a.innerText = text;
neww.appendChild(a);
document.getElementById('todotext').value = "";
}
</script>
</html>
Here is my code and I want to return an 'Alert' if someone submit empty form.
How should I do it ? Any help will be appreciated
Here's an image:
Is this what you want?
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>To Do List</h1>
<form>
<input autocomplete="off" autofocus id="todotext"
type="text">
<button onclick="todotext.value != '' ? serve() : alert('Input field is blank')" >Submit</button>
</form>
<ol id="add"></ol>
</body>
<script>
var todotext = document.getElementById('todotext');
function serve() {
const neww = document.getElementById('add');
let text = todotext.value;
const a = document.createElement('li');
a.innerText = text;
neww.appendChild(a);
document.getElementById('todotext').value = "";
}
</script>
</html>
String.prototype.isEmpty = function() {
return (this.length === 0 || !this.trim());
};
function serve(){
const neww = document.getElementById('add')
let text = document.getElementById('todotext').value;
if( text.isEmpty() ){
alert('cannot be blank');
return;
}
const a = document.createElement('li')
a.innerText = text
neww.appendChild(a)
document.getElementById('todotext').value = ""
}
<h1>To Do List</h1>
<form>
<input autocomplete="off" autofocus id="todotext"
type="text">
<input onclick="serve(); return false" type="submit">
</form>
<ol id="add"></ol>
add condition when append new element by checking the value of todoText
function serve(){
const neww = document.getElementById('add')
let text = document.getElementById('todotext').value
if(text == ""){
alert('field is required');
}
else{
const a = document.createElement('li')
a.innerText = text
neww.appendChild(a)
document.getElementById('todotext').value = ""
};
}
function serve(){
const neww = document.getElementById('add')
let text = document.getElementById('todotext').value
if(text.trim().length === 0){
alert("Field is empty");
}else{
const a = document.createElement('li')
a.innerText = text
neww.appendChild(a)
document.getElementById('todotext').value = ""
}
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>To Do List</h1>
<form>
<input autocomplete="off" autofocus id="todotext"
type="text">
<input onclick="serve(); return false" type="submit">
</form>
<ol id="add"></ol>
</body>
</html>
I started learning javascript about 2 weeks ago so I'm really new. I've been messing arround with forms and I can't figure out some stuff.
I made a form in HTML and want to validate it in Javascript.
What I've done so far:
if the the fields are empty and the user presses submit a red border will appear arround the field. The border dissapperas if the users writes something in the field.
What I want to do:
if there are no validation errors and the form is submitted I would like for a confirmation message to appear above the form. The message should be hidden initially and it should say something like: "Thank you for contacting us,(and the first name the user entered in the form)"
I also want to print every information from the input fields in the console after submit.
How can I do this using only vanilla Javascript?
function formValidation() {
if (document.myForm.fname.value == "") {
document.getElementById("first-name").style.border = "2px solid red";
return false;
} else {
document.getElementById("first-name").style.border = "";
};
if (document.myForm.lname.value == "") {
document.getElementById("last-name").style.border = "2px solid red";
return false;
} else {
document.getElementById("last-name").style.border = "";
};
var checkMale = document.getElementById("gender-m").checked;
var checkFemale = document.getElementById("gender-f").checked;
if (checkMale == false && checkFemale == false) {
alert("Please select gender");
return false;
};
if (document.myForm.texta.value == "") {
document.getElementById("area").style.border = "2px solid red";
return false;
} else {
document.getElementById("area").style.border = "";
};
return true;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="css/style.css">
<title>My Form</title>
</head>
<body>
<form id="my-form" name="myForm" action="#" onsubmit="event.preventDefault(); formValidation();">
<div id="msg">Thank you for contacting us, </div>
<input type="text" name="fname" id="first-name" placeholder="First Name"> <br>
<input type="text" name="lname" id="last-name" placeholder="Last Name"> <br>
<label for="gender">Gender:</label> <br>
<input type="radio" name="gender" id="gender-m"> Male <br>
<input type="radio" name="gender" id="gender-f"> Female <br>
<textarea name="texta" id="area" cols="30" rows="10"></textarea> <br>
<button type="submit">Submit</button>
</form>
<script src="index.js"></script>
</body>
</html>
You can do it like this :
function formValidation() {
if (document.myForm.fname.value == "") {
document.getElementById("first-name").style.border = "2px solid red";
return false;
} else {
document.getElementById("first-name").style.border = "";
};
if (document.myForm.lname.value == "") {
document.getElementById("last-name").style.border = "2px solid red";
return false;
} else {
document.getElementById("last-name").style.border = "";
};
var checkMale = document.getElementById("gender-m").checked;
var checkFemale = document.getElementById("gender-f").checked;
if (checkMale == false && checkFemale == false) {
alert("Please select gender");
return false;
};
if (document.myForm.texta.value == "") {
document.getElementById("area").style.border = "2px solid red";
return false;
} else {
document.getElementById("area").style.border = "";
};
var success = true;
if(success){
var data = document.getElementById("first-name").value+','+document.getElementById("last-name").value;
console.log(data);
var html = '';
html +='Thank you for contacting us,'+document.getElementById("first-name").value;
document.getElementById("msg").innerHTML = html;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="css/style.css">
<title>My Form</title>
</head>
<body>
<form id="my-form" name="myForm" action="#" onsubmit="event.preventDefault(); formValidation();">
<div id="msg"></div>
<input type="text" name="fname" id="first-name" placeholder="First Name"> <br>
<input type="text" name="lname" id="last-name" placeholder="Last Name"> <br>
<label for="gender">Gender:</label> <br>
<input type="radio" name="gender" id="gender-m"> Male <br>
<input type="radio" name="gender" id="gender-f"> Female <br>
<textarea name="texta" id="area" cols="30" rows="10"></textarea> <br>
<button type="submit">Submit</button>
</form>
<script src="index.js"></script>
</body>
</html>
When everything in the formValidation() function is validated then the code will set a flag success = true. If the value of success is true we can set a form submission successful message.