form validation dynamic created not working - javascript

I have some fields (created dynamically) in a page and I am trying to each element on form submit .Bellow code is sample ,only txtAge field validate, txtName not validating .Is there any option to validate each field with bellow code?
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script>
function txtName_FormValidation() {
document.getElementById('entryForm').onsubmit = function (e) {
if (document.getElementById('txtName').value.length <= 0) {
alert(1)
document.getElementById('span_txtName').innerHTML = 'Please Enter Name.'
return false;
};
}
}
function txtAge_FormValidation() {
document.getElementById('entryForm').onsubmit = function (e) {
if (document.getElementById('txtAge').value.length <= 0) {
alert(2)
document.getElementById('span_txtAge').innerHTML = 'Please Enter Age.'
return false;
};
}
}
</script>
</head>
<body onload="txtName_FormValidation(); txtAge_FormValidation()">
<form id="entryForm">
<input type="text" id="txtName" />
<span id="span_txtName"></span>
<br />
<input type="text" id="txtAge" />
<span id="span_txtAge"></span>
<br />
<button type="submit" value="Sebmit">Submit</button>
</form>
</body>
</html>

Why don't you do like this?
calling all validations from same function?
<script>
document.getElementById('entryForm').onsubmit = function(e){
txtName_FormValidation(e);
txtAge_FormValidation(e);
}
function txtName_FormValidation(e) {
if (document.getElementById('txtName').value.length <= 0) {
alert(1)
document.getElementById('span_txtName').innerHTML = 'Please Enter Name.'
return false;
};
}
function txtAge_FormValidation(e) {
if (document.getElementById('txtAge').value.length <= 0) {
alert(2)
document.getElementById('span_txtAge').innerHTML = 'Please Enter Age.'
return false;
};
}
</script>

You are replacing the first onsubmit event, for this reason only dispatch the second function.
You can try this:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('entryForm').onsubmit = function (e) {
e.preventDefault();
if (document.getElementById('txtName').value.length <= 0) {
alert(1)
document.getElementById('span_txtName').innerHTML = 'Please Enter Name.'
};
if (document.getElementById('txtAge').value.length <= 0) {
alert(2)
document.getElementById('span_txtAge').innerHTML = 'Please Enter Age.'
};
}
}, false);
</script>
</head>
<body >
<form id="entryForm">
<input type="text" id="txtName" />
<span id="span_txtName"></span>
<br />
<input type="text" id="txtAge" />
<span id="span_txtAge"></span>
<br />
<button type="submit" value="Sebmit">Submit</button>
</form>
</body>
</html>

Related

how to add enter key to calculate taxes?

id like to know how i can add onclick="calculer" to work with enter keyboard shortcut too. ive tried many code like this one
document.body.onkeydown = function(e) {
if (e.keyCode == 13)
validatePass();
};
but nothing seems to work. sorry im a begginer at school only beeing able to post was complicated to me :P would be much appreciated
<html>
<head>
<title>Page Title</title>
<meta charset="UTF-8" />
<script src="javascript.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css" />
<script>
function calculer() {
montant = Number(document.getElementById("montant").value);
taxe = (montant * 14.975) / 100;
total = (montant * 114.975) / 100;
ment.getElementById("taxe").value = taxe + " $";
ment.getElementById("total").value = total + " $";
}
</script>
</head>
<body>
Montant:
<br />
<input type="number" id="montant" />
<br /><br />
Taxe:
<br />
<input type="text" id="taxe" placeholder="$$$$$$$$$$$$$$$$$$$$$$" readonly />
<br /><br />
Résultat:
<br />
<input type="text" id="total" placeholder="$$$$$$$$$$$$$$$$$$$$$$" readonly />
<br /><br />
<button type="button" onclick="calculer()">Calculer</button>
</body>
</html>
const elementOne = document.getElementById('taxe');
const elementTwo = document.getElementById('taxe');
elementOne.addEventListener('keyup',(e) => {
if(e.keyCode == 13){
calculer()
//use the same process for elementTwo
}
})
You should attach the event listener to the document.
Here's how you can do it:
document.addEventListener("keyup", e => {
if (e.keyCode == 13) {
calculer();
}
});

SubmitForm when pressing Enter (To-do-list)

I was building a To Do List with HTML and JavaScript and now I want to add input not only with the submit button but also if i press enter anywhere on the page. I mainly wanna use javascript only to create that function, no "onclick" feature in html.
<!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="style.css" />
<title>To do app</title>
</head>
<body>
<h1>To-Do List</h1>
<form>
<input type="text" placeholder="Add an item!" id="inputField" />
</form>
<button id="submit">Submit</button>
<button id="clear">Clear List</button>
<div id="output"></div>
<script src="script.js"></script>
</body>
</html>
----------------------------------
document.getElementById("submit").addEventListener("click", function () {
submitForm();
});
document.getElementById("clear").addEventListener("click", function () {
document.getElementById("inputField").value = "";
document.getElementById("myOl").innerHTML = "";
});
function submitForm() {
let input = document.getElementById("inputField").value;
let ol = document.createElement("ol");
ol.setAttribute("id", "myOl");
document.body.appendChild(ol);
let y = document.createElement("LI");
let t = document.createTextNode(`${input}`);
y.appendChild(t);
document.getElementById("myOl").appendChild(y);
document.getElementById("inputField").value = "";
}
You could use keypress event listner with document.addEventListener and check for the event.key, event.keyCode and event.which combination to check for enter key.
Dont forget to use event.preventDefault() to prevent reload of page.
document.getElementById("submit").addEventListener("click", function () {
submitForm();
});
document.getElementById("clear").addEventListener("click", function () {
document.getElementById("inputField").value = "";
document.getElementById("myOl").innerHTML = "";
});
document.addEventListener('keypress', function (e) {
const code = (e.keyCode ? e.keyCode : e.which);
if (e.key === 'Enter' || code == 13) {
submitForm();
e.preventDefault();
}
});
function submitForm() {
let input = document.getElementById("inputField").value;
let ol = document.createElement("ol");
ol.setAttribute("id", "myOl");
document.body.appendChild(ol);
let y = document.createElement("LI");
let t = document.createTextNode(`${input}`);
y.appendChild(t);
document.getElementById("myOl").appendChild(y);
document.getElementById("inputField").value = "";
}
<h1>To-Do List</h1>
<form>
<input type="text" placeholder="Add an item!" id="inputField" />
</form>
<button id="submit">Submit</button>
<button id="clear">Clear List</button>
<div id="output"></div>
You can use key up event.
document.addEventListener('keyup', keypress);
function keypress(e){
e.preventDefault()
if (e.key === 'Enter' || e.keyCode === 13) {
submitForm();
}
}
added e.preventDefault() to avoid form submission
https://developer.mozilla.org/en-US/docs/Web/API/Document/keyup_event

How do I create an error alert for an invalid input?

I am creating a date input and I want an error alert if the date input is left blank.
currently I have and it doesnt work:
<!Doctype html>
<html>
<head>
<script type="text/javascript">
function validateDate(value) {
var a = document.getElementById("date").value;
if (a = = = "") {
window.alert("Error");
return false;
}
}
</script>
</head>
<body>
<h1>Tee Time Sign-up Form</h1>
<form>
<div id="teeDate">
Date:<input type=“date” id=“date” name=“date”><br>
<button id=teeTime onClick="validateDate()">Submit</button><br>
</div>
</form>
</body>
</html>
Do not put spaces in your operators, use === not = = =, a better use to say if a !== "" if a is NOT an empty string
Try this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Tee Time Sign-up Form</h1>
<form>
<div id="teeDate">
Date:<input type="date" id="date" name="date" /><br />
<button id="teeTime">Submit</button><br />
</div>
</form>
<script type="text/javascript">
var button = document.getElementById("teeTime");
function validateDate(value) {
if (value === "") {
window.alert("Error");
return false;
}
}
button.addEventListener("click", function (e) {
var value = document.getElementById("date").value;
validateDate(value);
});
</script>
</body>
</html>

Confirmation message for form submission after validations in JavaScript

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.

How Can I use form items in javascript

I want to use HTML form elements in JavaScript. I used them like this but it doesn't work:
<form name="M">
<input name="in1" type="text" id="in1">
<input type="button" name="btn1" id="btn1" value="Check" onclick="f1()">
</form>
<script src="script.js"></script>
...and the JavaScript code was like this:
var s1 = 60;
function f1() {
``
if (document.M.elements[0] == s1) {
window.location = 'tick.htm';
} else {
window.location = 'cross.htm';
}
}
What is wrong here?
Just to give some clarification on why this was not working. In the test, document.M.elements[0] is a reference to the input object, not the value of the input. Using document.M.elements[0].value gives us the current value of the input.
//Ignore this, for display only.
function output(msg) {
var element = document.getElementById('output');
element.innerHTML = msg;
};
function f1() {
var s1 = 60;
if (document.M.elements[0].value == s1) {
output('Pass');
} else {
output('Fail');
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<form name="M">
<input name="in1" type="text" id="in1">
<input type="button" name="btn1" id="btn1" value="Check" onclick="f1()">
</form>
<b id="output"></b>
</body>
</html>

Categories