My console.log keeps saying NaN is false while it isn't - javascript

So I have this code and when the user types a number it should log "this is a valid number" in the console and else it should log "this is not a valid number". But my code keeps logging "this is a valid number". And I have to use isNaN.
Please be easy on me, I'm just starting JavaScript.
This is my HTML code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Postcode</title>
<script src="postcode.js">
</script>
</head>
<body>
<form class="form">
<label for="postcode">Postcode: </label>
<input type="text" id="postcode">
</form>
</body>
</html>
And this is my JavaScript code:
window.addEventListener("load", init);
function init() {
alert("Content loaded");
var nameInput = document.getElementById('postcode');
document.querySelector('form.form').addEventListener('submit', function (e) {
//prevent the normal submission of the form
e.preventDefault();
if (nameInput === isNaN || nameInput === "") {
console.log("this is not a valid number!");}
else if (nameInput !== isNaN) {
console.log("this is a valid number!");}
});
}

There's something in javascript called NaN (Not A Number), then there's a function that checks if something is NaN appropriately called isNaN().
You're checking if your variable is the exact same as the isNaN function, which of course it's not, as nameInput is an object, or more correctly a HTML input element.
What you want is probably to get the value of the input, and check if it's "Not A Number", or just an empty string (which seems like an uneccessary check here)
if (isNaN(nameInput.value) || nameInput.value === "") {

Use isNaN(...) to check if a something is Not A Number:
isNaN('a'); // true
And also nameInput refers to a DOM node, get the value (or innerHTML):
isNaN(nameInput.value)
And your full code:
window.addEventListener("load", init);
function init() {
var nameInput = document.getElementById('postcode');
document.querySelector('.form').addEventListener('submit', function (e) {
e.preventDefault();
if (!nameInput.value || isNaN(nameInput.value)) {
console.log("this is not a valid number!");}
else {
console.log("this is a valid number!");}
}
});
}

isNaN is a function. If you do nameInput === isNaN, you check if nameInput is pointing to the function isNaN.
What you want to do, is to call the function: isNaN(nameInput).
Also nameInput is a HTML DOM Element. You first have to get the value from it: nameInput.value
Just do:
if (isNaN(nameInput.value)) {
console.log("this is not a valid number!");}
else {
console.log("this is a valid number!");
}

Related

Function "main" calls input listener, returns input value but logs undefined. How to make it sync and log input value each time?

I have a function named main, within which I am calling an input event listener and checking if the user enters valid input. If the input is correct, I am returning the input value to the main function. However, when I attempt to console.log the value, it returns as undefined. How can I make this function work synchronously in order to achieve the desired outcome, while also noting that I want to console.log the input value every time the user inputs a correct value?
[HTML CODE]
<!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>Demo Code</title>
</head>
<body>
<body>
<form action="" method="get">
<input type="text" name="name" id="name" placeholder="Enter Your Name">
<label id="error"></label>
</form>
</body>
</html>
[JavaScript Code]
function validator(regex, input) {
/*This function takes regex and user input and returns true or false*/
const re = regex;
return re.test(input);
}
function main() {
const inputName = document.querySelector('#name');
const errorName = document.querySelector('#error');
inputName.addEventListener('input', () => {
// regular expression string only alphabets and no space
isValid = validator(/^[a-z]*$/, inputName.value);
if (isValid) {
errorName.innerHTML = "Valid Name";
// it should only returns when isValid is true,
// as later I want to use correct inputName.value in some another function
return inputName.value;
}
else {
errorName.innerHTML = "Invalid Name";
}
});
}
let name = main()
console.log(name) // I want to console.log the value every time when inputName value returns the correct name, but in this case it prints undefined
If you want to console log the value every time when inputName value returns the correct name
Than keep the console.log inside if statement which is inside input.addEventListener something like this
if (isValid) {
Console.log(inputName.value); ...
}```
You need to set it up so the validation will occur after the user inputs something into the name input field:
const nam=document.getElementById("name"),
err=document.getElementById("error");
nam.addEventListener("input",ev=>{
err.textContent="";
if (nam.value.match(/^[a-z]*$/))
console.log(nam.value);
else err.textContent=`${nam.value} does not fulfil the validation-regex (/^[a-z]*$/)`;
});
<form action="" method="get">
<input type="text" name="name" id="name" placeholder="Enter Your Name">
<label id="error"></label>
</form>
Please check out this code and let me know if that is what you want
You can simplify this code even more to make it readable.
function main() {
const inputName = document.querySelector("#name");
const errorName = document.querySelector("#error");
inputName.addEventListener("input", () => {
let isValid = validator(/^[a-z]*$/, inputName.value);
if (isValid) {
errorName.innerHTML = "Valid Name";
console.log(inputName.value);
return inputName.value;
} else {
errorName.innerHTML = "Invalid Name";
}
});
function validator(regex, input) {
const re = regex;
return re.test(input);
}
}
main();

If/Else and typeof problems

The problem is, I have no idea why this code doesn't work. I searched everywhere!
What this code does, is to take information from a number box, then display a message if the users inputs text(an error), and display a success message, if the user inputs number.
HTML ->
<input type="number" id="number">
<button onclick="makeTrack()">Make Track</button>
<div><div>
JS -> Where the problem starts!
function makeTrack() {
var e = document.getElementById("number").value;
if(typeof e === "number";) {
alert("It works!");
} else if(typeof e === "string") {
alert("Please input a number!");
}
}
document.getElementById("number").value
The value of all elements will always be a string; JS doesn't try to outsmart you and guess whether it's a number or not (that would be disastrous!). Try parsing it first, like this:
function makeTrack() {
var e = parseInt(document.getElementById("number").value, 10);
if(!isNaN(e)) {
alert("It works!");
} else {
alert("Please input a number!");
}
}
Note that this will interpret an input of "12345 this is a string" as 12345. If this is undesirable, try something like this:
var e = document.getElementById("number").value;
if (/^[0-9]+$/.test(e)) {
// good
e = parseInt(e, 10); // make sure to still convert it to a number!
}

Passing an id through a function parameter

Trying to get a value of a textbox by passing the ID into a function parameter. Should be easy but can't wrap my head around it.
JavaScript:
function checkfield(id)
{
var field = document.getElementById(id);
if (isNaN(field) == true)
{
alert('You must enter a valid number!');
field.value = "0";
field.focus(textbox);
field.select(textbox);
return false;
}
return true;
}
HTML:
<input type="text" id="numbox19" name="customerZip" style="width: 240px" value=" " onchange="checkfield('numbox19')"/>
Error Message
Error: Unable to get property 'value' of undefined or null reference
Your ID is 19, but you're passing numberbox19 to the Javascript function. There are also several syntax errors.
Try:
<input type="text" id="numberbox19" name="customerZip" style="width: 240px" value=" " onchange="checkfield(this)"/>
And Javascript:
function checkfield(field) // <-- we passed the field in directly from the HTML, using 'this'
{
alert(field.value);
if (isNaN(field.value)) // check the value, not the field itself!
{
alert('You must enter a valid number!');
field.value = "0";
field.focus(); // not "field.focus(textbox);"
return false;
}
return true;
}
The good thing here is, if you ever decide to change the ID for any reason, you only have to change it in one place instead of two.
the id of your input is "19" not "numberbox19"

Why does the order of Boolean values affect this program?

I created a basic program where user input is turned into an alert on submission. I can't figure out why the program only works as intended if I use false rather than true as the first condition in my if/else statement. I'm sure this is very basic but I've failed to find anything of relevance. After a long search I decided to post the question. Any answers will be greatly appreciated.
The HTML:
<form id="greetingForm">
<input type="text" name="userInput" id="userInput"/>
<input type="submit" value="click" id="submit"/>
</form>
The broken script:
function output(){
var input = document.getElementById('userInput').value;
if(input == true){
alert(input);
}else{
alert('Say something!');
}
}
function init(){
var greetingForm = document.getElementById('greetingForm');
greetingForm.onsubmit = output;
}
window.onload = init;
The working script:
function output(){
var input = document.getElementById('userInput').value;
if(input == false){
alert('Say something!');
}else{
alert(input);
}
}
function init(){
var greetingForm = document.getElementById('greetingForm');
greetingForm.onsubmit = output;
}
window.onload = init;
The variable input will never be equal to the boolean true because it is a string. Try changing it to:
function output(){
var input = document.getElementById('userInput').value;
if(input != ""){
alert(input);
}else{
alert('Say something!');
}
}
To clarify ferd tomale's answer, it's one of the "weird" type conversion cases where a check on equality to true does not behave in the same way as check on equality to false.
"" == false -> true
"a" == false -> false, but
"" == true -> false
"a" == true -> false
You can switch to using typesafe comparison operators (===, !==), which behave much more predictable, but then you'll have to convert values to the correct type yourself. Or you can learn the quirks of JS's automatic type conversion when you use == or !=.
Because your input is a string. And string == true will be false.
You can set breakpoints to check them.

Javascript validation not working?

What's wrong in it why it's not working...
<script language="JavaScript" type="text/javascript">
//function to check empty fields
function isEmpty(strfield1, strfield2) {
//change "field1, field2 and field3" to your field names
strfield1 = document.forms[0].name.value
strfield2 = document.forms[0].email.value
//name field
if (strfield1 == "" || strfield1 == null || !isNaN(strfield1) || strfield1.charAt(0) == ' ') {
alert( "Name is a mandatory field.\nPlease amend and retry.")
return false;
}
//EMAIL field
if (strfield2 == "" || strfield2 == null || !isNaN(strfield2) || strfield2.charAt(0) == ' ') {
alert(" Email is a mandatory field.\nPlease amend and retry.")
return false;
}
return true;
}
//function to check valid email address
function isValidEmail(strEmail){
validRegExp = /^[^#]+#[^#]+.[a-z]{2,}$/i;
strEmail = document.forms[0].email.value;
// search email text for regular exp matches
if (strEmail.search(validRegExp) == -1) {
alert('A valid e-mail address is required.\nPlease amend and retry');
return false;
}
return true;
}
//function that performs all functions, defined in the onsubmit event handler
function check(form)){
if (isEmpty(form.field1)){
if (isEmpty(form.field2)){
if (isValidEmail(form.email)){
return true;
}
}
}
}
return false;
}
</script>
It doesn't do anything I don't understand what's going there and in form I put this too
<form onsubmit="return check(this);" action="sendquery.php" name="contquery">
First glance: too many brackets as shown by #FishBasketGordo so I will not repeat
Second glance - you pass the field and do not test the field value
Third glance: You do not pass the correct names to the function
Fourth glance - isEmpty returns false when empty. It should return true
I fixed all those
DEMO HERE
Complete page to show where what goes. Updated to do unobtrusive event handling on the form
<html>
<head>
<title>Validation</title>
<script type="text/javascript">
// trim for IE
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
//function to check empty fields
function isEmpty(objfld) {
var val = objfld.value;
if (val.trim() == "" || val == null) {
alert(objfld.name+" is a mandatory field.\nPlease amend and retry.");
objfld.focus();
return true;
}
return false;
}
//function to check valid email address
function isValidEmail(objEmail){
var validRegExp = /^[^#]+#[^#]+.[a-z]{2,}$/i;
var strEmail = objEmail.value;
if (strEmail.match(validRegExp)) return true;
alert('A valid e-mail address is required.\nPlease amend and retry');
objEmail.focus();
return false;
}
//function that performs all functions, defined in the onsubmit event handler
function validate(form) {
if (isEmpty(form.name)) return false;
if (isEmpty(form.email)) return false;
return isValidEmail(form.email);
}
window.onload=function() {
document.getElementById("form1").onsubmit=function() {
return validate(this);
}
}
</head>
<body>
<form id="form1">
Name:<input type="text" name="name" /><br/>
Email:<input type="text" name="email" /><br/>
<input type="submit" />
</form>
</body>
</html>
Probably the main reason it isn't working is the syntax errors:
// Syntax error ----v
function check(form)){
if (isEmpty(form.field1)){
if (isEmpty(form.field2)){
if (isValidEmail(form.email)){
return true;
}
}
}
}
// The return statement should be above the previous closing bracket
// and the final closing bracket removed.
return false;
}
There's an extra closing paren on the first line, and there are too many closing brackets. If you open up this up in FireBug or Chrome Developer Tools or a similar tool, it would tell you about this automatically.

Categories

Resources