HTML/JS code to display Error Message if Input is Wrong - javascript

I am trying to write an HTML5 - JS Program that displays an Error Message IF the User Input is Empty. But I am not able to get the "Error Message", even thou I can't seem to find any issues.
I am a complete beginner and the Video Tutorial I am using doesn't have any User Support.
Please Help.
I have tried all I know but no avail.
<!DOCTYPE html>
<html>
<head>
<title>Error Message Display</title>
<script type="text/javascript">
function displayInput()
{
var testInput = document.getElementById("name").value;
if (testInput.lenght == 0)
{
document.getElementById("para").innerHTML = "NOOOO";
}else
document.getElementById("para").innerHTML = testInput;
}
</script>
</head>
<body>
<input id="name" type="text"/>
<button onclick="displayInput();">Show The Text</button>
<p6 id="para"></p6>
</body>
</html>
If the Input is Empty an Error Message i.e NOOOO should display.

hi you made spelling mistake in length property of element
it should not be lenght
function displayInput()
{
let el = document.getElementById("name");
let para = document.getElementById("para")
var testInput = el.value;
if (testInput.length == 0)
{
para.innerHTML = "NOOOO";
}
else{
para.innerHTML = testInput;
}
}
<!DOCTYPE html>
<html>
<head>
<title>Error Message Display</title>
</head>
<body>
<input id="name" type="text"/>
<button onclick="displayInput();">Show The Text</button>
<p6 id="para"></p6>

Related

I have an if else statement that I dont know how to make the else part relevent

const newInput = document.querySelector('input');
const h1 = document.querySelector('h1');
newInput.addEventListener('change', function(){
if (newInput != ''){
h1.innerText = 'Welcome ' + newInput.value
} else {
h1.innerText = 'Enter Your Username';
}
});
<head>
<title>Input Event</title>
<!--LEAVE THESE LINES ALONE, PLEASE! THEY MAKE THE LIVE PREVIEW WORK!-->
<!-- <script src="node_modules/babel-polyfill/dist/polyfill.js" type="text/javascript"> </script> -->
<!-- <script src="https://unpkg.com/#babel/standalone/babel.min.js"></script> -->
</head>
<body>
<h1>Enter Your Username</h1>
<input type="text" id="username">
<script src="InputEvent.js"></script>
</body>
</html>
My if else statement appears to be ignored unless I change it to (if (newInput === 'a value' ) at which point it stops the function.
I don't understand why I can make the if statement relevant but it wont continue to the else part of the code.
Can anyone shed some light?
You need to use the .value property for newInput.value. newInput is a DOM node and you need to check if the value is empty.
const newInput = document.querySelector('input');
const h1 = document.querySelector('h1');
newInput.addEventListener('change', function() {
if (newInput.value !== '') {
h1.innerText = 'Welcome ' + newInput.value
} else {
h1.innerText = 'Enter Your Username';
}
});
<head>
<title>Input Event</title>
</head>
<body>
<h1>Enter Your Username</h1>
<input type="text" id="username">
<script src="InputEvent.js"></script>
</body>
</html>
The problem is that you are not accessing the value correctly. You either need newInput.value or event.target.value to get the value of the input. Working example of the specified problem https://codesandbox.io/s/clever-forest-18vme?file=/InputEvent.js:287-328

Email validation function not working properly with form button

I am working on my final project for my JS class. I have reached a bit of a roadblock, and was hoping for a little guidance.
I am looking to take the input (all coding needs to be done in JS) for email and validate. If the email is validated, then it should send the input to be written on a new webpage. If the the input is not valid, there should be an alert and the user should then reenter a proper email address.
This is just a portion of the project. I am creating having the user enter input information for a resume to written on the new page.
With the current state of the code, it is popping up the alert box that the email is not valid (even when it is). I have gotten it write if I take away the validation portion. However, it writes "undefined".
//html
<!DOCTYPE html>
<html lan= "en">
<head>
<title>WEB 115 Final Project</title>
</head>
<body>
<script src= "projectJS.js"></script>
<br><br>
<form onsubmit="validateEmail()">
<input type="submit" value="Create Resume">
</form>
</body>
</html>
//JS email
var email = document.createElement("p");
email.innerText = "Enter Email Address:";
document.body.appendChild(email);
var inputEmail = document.createElement("input");
inputEmail.type = "text";
inputEmail.setAttribute("id", "email");
document.body.appendChild(inputEmail);
//email validation on click form button from html
function validateEmail(inputEmail) {
var re = /^[^\s#]+#[^\s#]+\.[^\s#]+$/;
var testRe = re.test(inputEmail);
testRe;
if (testRe != true) {
window.alert("Invalid Email Address. Please Reenter");
}
else {
var openWindow = window.open("");
openWindow.document.write(inputEmail);
}
}
If anybody would be so kind as to advise on this issue, I would be grateful. Thank you.
The issue was simply that you were passing inputEmail as the argument to test() when what you actually want to test is inputEmail.value. Demonstration below should work:
const validateEmail = (e, inputEmail) => {
e.preventDefault();
if (/^[^\s#]+#[^\s#]+\.[^\s#]+$/.test(inputEmail.value)) {
console.log(`${inputEmail.value} is a VALID email address :)`);
return true;
}
console.log(`${inputEmail.value} is an INVALID e-mail address. Please fix!`);
return false;
};
const init = () => {
var email = document.createElement("p");
email.innerText = "Enter Email Address:";
document.body.appendChild(email);
var inputEmail = document.createElement("input");
inputEmail.type = "text";
inputEmail.setAttribute("id", "email");
document.body.appendChild(inputEmail);
document.querySelector('form').addEventListener('submit', e => validateEmail(e, inputEmail));
};
init();
<head>
<title>WEB 115 Final Project</title>
</head>
<body>
<script src="projectJS.js"></script>
<br><br>
<form>
<input type="submit" value="Create Resume">
</form>
</body>
add .value to get Input email like this:
var testRe = re.test(inputEmail.value);
I've solved your problem. Now it's working. Check it.
var email = document.createElement("p");
email.innerText = "Enter Email Address:";
document.body.appendChild(email);
var inputEmail = document.createElement("input");
inputEmail.type = "text";
inputEmail.setAttribute("id", "email");
document.body.appendChild(inputEmail);
//email validation on click form button from html
function validateEmail() {
var inputEmail = document.getElementById('email').value; //get email id
var re = /^[^\s#]+#[^\s#]+\.[^\s#]+$/;
var testRe = re.test(inputEmail);
testRe;
if (testRe != true) {
window.alert("Invalid Email Address. Please Reenter");
}
else {
var openWindow = window.open();
openWindow.document.write(inputEmail);
}
}
<!DOCTYPE html>
<html lan= "en">
<head>
<title>WEB 115 Final Project</title>
</head>
<body>
<script src= "projectJS.js"></script>
<br><br>
<form onsubmit="validateEmail()">
<input type="submit" value="Create Resume">
</form>
</body>
</html>

Javascript can't get form to validate

I'm having problems getting my form to validate with Javascript. I've tried a bunch of different things, but I just can't get it to work. It's possible I'm missing something completely basic, I am pretty new at this. Please let me know what I could possibly change.
<!DOCTYPE html>
<html lang = "en">
<head>
<title> </title>
<meta charset = "utf-8" />
</head>
<body>
<script lang = "text/javascript">
document.getElementById("myForm").onsubmit = validateForm();
function zipcheck(sZip)
{
var postalRegex = /^d{5}(-\d{4})?$/;
return postalRegex.test(sZip);
}
function validateForm()
{
if (zipcheck(document.getElementById("zip"))
return true;
else
{
alert(document.getElementById("zip") + " is not a valid zip code");
return false;
}
}
</script>
<form id = "myForm" action = "" >
<p>
<label> Zip Code
<input type = "text" id = "zip" />
</label>
<input type = "submit" name = "submit" />
</p>
</form>
</body>
</html>
The Problem your are, checking the HTML Element not the Value. It should be document.getElementById("zip").value
document.getElementById("myForm").onsubmit = validateForm;
function zipcheck(sZip)
{
var postalRegex = /^d{5}(-\d{4})?$/;
return postalRegex.test(sZip);
}
function validateForm()
{
if (zipcheck(document.getElementById("zip").value)){
return true;
}else
{
alert(document.getElementById("zip").value + " is not a valid zip code");
return false;
}
}
<!DOCTYPE html>
<html lang = "en">
<head>
<title> </title>
<meta charset = "utf-8" />
</head>
<body>
<form id = "myForm" action="/test" method="get" >
<p>
<label> Zip Code
<input type = "text" id = "zip" />
</label>
<input type = "submit" name = "submit" />
</p>
</form>
</body>
</html>
here is a working sample on jsfiddler https://jsfiddle.net/u9suy516/
Optional Information: when using addEventListener you would also have to use the preventDefault() function on the passed event Parameter, but not need the return statments.
function validateForm(event)
{
if (!zipcheck(document.getElementById("zip").value)) {
alert(document.getElementById("zip").value + " is not a valid zip code");
event.preventDefault();
}
}

JavaScript Quiz Not Working

I am trying to make a little quiz to study.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Quiz</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body>
<div id="question"></div>
<form>
<input type="text" id="answer">
<button onClick="check()">Check</button>
</form>
<script>
var spanish = new Array("Hola", "Sí", "No");
var english = new Array("Hello", "Yes", "No");
var x = Math.floor(Math.random()*3);
document.getElementById("question").innerHTML = english[x];
var attempt = document.getElementById("answer");
var correct = spanish[x];
function check(){
if(attempt == correct){
alert("Correct");
}else{
alert("Fail");
};
};
</script>
</body>
</html>
It is returning Fail no matter if I am right or not. Do you know how to fix this? I looked around but could not figure out what is wrong. Thanks.
You need to check for attempt upon clicking the button. You're currently checking it on page load (so it's always an empty string, which is causing correct == attempt to be false). Also, you need to grab the value, not the element.
So, change your function to:
function check() {
var attempt = document.getElementById("answer").value;
if (attempt == correct) {
alert("Correct");
} else {
alert("Fail");
};
};
See here: http://jsfiddle.net/ykZHa/

Cant remove childnode without making childNode (message) not showing at all

I've have tried alot of different ways with removing the child and nothing has worked so faar, well it has to some degree, either i have no messages or i keep getting message that just add to the span without deleting the other
Tried reading up on how to remove the child, and have tried every different ways i've found to remove it, my code might be wrong on creating the child and append it etc. since it's the first time i use this way. Been trying with a while loop to remove, and the one that is already outcommented in the code, and with firstChild. and with different names instead of msg.
My code looks like this in my script:
function validateName(input, id)
{
var res = true;
var msg = document.getElementById(id);
var error = document.createElement("span");
var errorMsg = "";
if (input == "" || input < 2) {
res = false;
// removeChildren(msg);
errorMsg = document.createTextNode("Input is to short!");
error.appendChild(errorMsg);
id.appendChild(error);
}
if (input >= 2 && input.match(/\d/)) {
res = false;
// removeChildren(msg);
errorMsg = document.createTextNode("Name contains a number!");
error.appendChild(errorMsg);
id.appendChild(error);
}
if (input >= 2 && !input.match(/\d/)) {
res = true;
// removeChildren(msg);
}
return res;
}
My small test page:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="Validator.js"></script>
<script>
function v1(e,id) {
if(validateName(document.form1.namefield.value, id) == false) {
document.getElementById("be").src="NotOkSmall.jpg";
}
if(validateName(document.form1.namefield.value) == true) {
document.getElementById("be").src="OkSmall.jpg";
}
}
</script>
</head>
<body>
<h1>Validation testing, HO!</h1>
<form name="form1" action="submit">
<div id="div1">
<input type="text" name ="namefield" id="f1" onkeydown="v1(be, div1)" >
<image id="be" src="NotOkSmall.jpg" alt="OkSmall.jpg" />
</div>
<input type="button" value="GO" onClick="v1(be)">
</form>
</body>
</html>
If anyone have any ideas to make it work I for one, would be a very happy guy :), as i have said before i am not even sure the creation of child is the correct way in this case. but as it works when i have removed removeChildren, it does write the correct messages, just dont delete any of them. So something must work..
Thanks.
You had some errors in your code like id.appendChild(error); where you had to use msg.appendChild(error);. Anyway I don't see a need to append/remove child nodes in this case. Just use hidden error placeholder and show it when you want to display an error message.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSP Page</title>
<script src="Validator.js"></script>
<script>
function v1(imgId) {
var img = document.getElementById(imgId),
val = document.form1.namefield.value;
img.src = img.alt = validateName(val)
? "OkSmall.jpg"
: "NotOkSmall.jpg";
}
</script>
</head>
<body>
<h1>Validation testing, HO!</h1>
<form name="form1" action="submit">
<div id="div1">
<input type="text" name ="namefield" id="f1" onkeyup="v1('be');" >
<image id="be" src="NotOkSmall.jpg" alt="NotOkSmall.jpg" />
<span id="error-message" class="invis"></span>
</div>
<input type="button" value="GO" onClick="v1('be');">
</form>
</body>
</html>​​​​​​​​​
CSS:
​.invis {
display: none;
}​
JavaScript:
function validateName(input) {
var res = true,
errorMsg,
errorContainer = document.getElementById('error-message');
if(input.length < 2) {
res = false;
errorMsg = "Input is to short!";
}
if(input.length >= 2 && /\d/.test(input)) {
res = false;
errorMsg = "Name contains a number!";
}
if(res) {
errorContainer.style.display = 'none';
} else {
errorContainer.innerHTML = errorMsg;
errorContainer.style.display = 'inline';
}
return res;
}​
DEMO

Categories

Resources