If/Else and typeof problems - javascript

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!
}

Related

I want to add an alert in the if else statement. How do I do that?

I want to add an alert inside the if and else if. If the user does not enter anything in the prompt box the alert triggers. Also if the user enters a number the prompt it will say that the user entered a number. How do do that?
let myForm2 = document.querySelector('.form2');
let pDisplay1 = document.querySelector('.display4');
myForm2.addEventListener('submit', function(e) {
e.preventDefault();
let uname = document.querySelector('.inputName2').value;
if (uname == null) {
} else if (isNaN(uname) == false) {
} else {
pDisplay1.innerHTML = `Welcome to the program ${uname}`;
}
})
<p> Activity 6</p>
<form class="form2" method="get">
<label>Full Name: <input type="text" class="inputName2"></label>
<input type="submit">
</form>
<p class="display4"></p>
document.querySelector('.className').value will return a string.
string.trim() removes the whitespaces and if the length === 0 it means that the input is empty or has only whitespaces which you generally want to treat as empty. If you consider space is a valid input you don't have to use trim().
The + sign will convert a string into a number otherwise you could use parseInt(variable).
Number.isInteger(variable) will return true if the variable is an integer.
You could also write !isNaN(+uname) or +uname !== Number.NaN
myForm2.addEventListener('submit', function (e) {
e.preventDefault();
let uname = document.querySelector('.inputName2').value;
if (uname.trim().length === 0) {
alert('You should write something');
} else if (Number.isInteger(+uname)) {
alert('You wrote a number');
} else {
pDisplay1.innerHTML = `Welcome to the program ${uname}`;
}
});
Empty string is not equal to null, replace uname==null with uname=='', after the replacement, you can identify the situation that the user did not input, if it is more strict, you can also use trim to remove whitespace and then do condition review

Stop form whitespace when user pressing submit

Okay, so I have a form. Applied a function to it.
All I want to do is when the form is submitted it launches the function, it checks to see if there is white space and throws out a message. I have the following:
function empty() {
var x;
x = document.getElementById("Username").value;
if (x == "") {
alert("Please ensure you fill in the form correctly.");
};
}
<input type='submit' value='Register' onClick='return empty()' />
<input type='text' id="Username" />
This is fine for if someone pressed the space-bar once and enters one line of whitespace, but how do I edit the function so that no matter how many spaces of whitespace are entered with the space-bar it will always throw back the alert.
Thanks in advance. I am very new to JavaScript. So please be gentle.
Trim the string before testing it.
x = document.getElementById("Username").value.trim();
This will remove any whitespace at the beginning and end of the value.
I have made a function for the same, i added another checks (including a regular expresion to detect multiples empty spaces). So here is the code:
function checkEmpty(field){
if (field == "" ||
field == null ||
field == "undefinied"){
return false;
}
else if(/^\s*$/.test(field)){
return false;
}
else{
return true;
}
}
Here is an example working with jquery: https://jsfiddle.net/p87qeL7f/
Here is the example in pure javascript: https://jsfiddle.net/g7oxmhon/
Note: the function checkEmpty still be the same for both
this work for me
$(document).ready(function() {
$('#Description').bind('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9 .]/gi,
v = $(this).val();
if (r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
});
function checkEmpty(field) { //1Apr2022 new code
if (field == "" ||
field == null ||
field == "undefinied") {
return false;
} else if (/^\s*$/.test(field)) {
return false;
} else {
return true;
}
}

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

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!");
}

How to allow only numbers between 0 to 30 or A,D character in input using javascript?

Hi i have created a javascript function to only allow numbers between 0 to 30 and character A and D. I give an alert if it does not match the criteria but if the user clicks ok on the alert the values still remain in the input and can be updated in the database. I want that user should not be able to enter anything at all in the input box except character A , D and numbers between 0 to 30 like it is done in the case of input type=number we can only enter numbers. My javascript function is:-
function validate() {
var regex = /[ad0-9]/gi;
var txt = document.getElementById('txt').value;
var valid = true;
var error = '';
if (regex.test(txt)) {
if (!isNaN(txt)) {
if (!(parseInt(txt) >= 0 && parseInt(txt) <= 30)) {
valid = false;
error = 'Please enter between 0 to 30.'
}
}
}
else {
valid = false;
error = 'Please enter between 0 to 30, A or D'
}
if (!valid) {
alert(error);
}
}
The javascript works fine with validation but after clicking ok in alert value still remains there and it also gives error when input box is empty any way to avoid that. Is there any other better way to create the function or can it done by using jquery. I am new to jquery if it is possible to do it with jquery it would be great. I would be highly gratefull if anybody can help.
You may try this code example.
function validate(box) {
var val = box.value;
if (!/^[AD]?$/.test(val) && isNaN(val) || (0 > val || 30 < val)) {
box.value = '';
alert('Only A or D or 0-30');
}
}
<input type='text' value='30' onblur='validate(this);' />
The best solution would be to check it at the moment when you are inserting it in the database.
if(txt.replace(/ /g, '').length == 0) {
// text is empty
return; // get out of function
}
If you want to make sure there is no error when the text is empty, you can do this. The .replace part is to ensure that if the text input is filled with only spaces, it is considered empty.
With the rest of the function:
function validate() {
var regex = /[ad0-9]/gi;
var txt = document.getElementById('txt').value;
var valid = true;
var error = '';
if(txt.replace(/ /g, '').length == 0) {
// text is empty
return; // get out of function
}
if (regex.test(txt)) {
if (!isNaN(txt)) {
if (!(parseInt(txt) >= 0 && parseInt(txt) <= 30)) {
valid = false;
error = 'Please enter between 0 to 30.'
}
}
}
else {
valid = false;
error = 'Please enter between 0 to 30, A or D'
}
if (!valid) {
alert(error);
}
}
How about replacing disallowed values so only the desired input is allowed. With this you won't be able to enter anything other than A, D and numbers 0 - 30:
$('input').on('input', function(e) {
this.value = this.value
.replace(/[^AD\d]/, '')
.replace(/(3)[1-9]/, '$1')
.replace(/(30)[0-9]/, '$1')
.replace(/([4-9])[0-9]/, '$1')
.replace(/([\d][\d])[\d]/, '$1');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" />
Note, it's still a good idea to do some server side validation.

How to return a light box error message from a function

I've created a basic form validation script that I want to return an error messages as a light box, rather than using an alert() message. I like the look of featherlight.js, but I can't figure out how to return it from a function? Any other suggestions would be greatly appropriated. Thanks in advance.
The featherlight.js repo
function validate() {
var name = document.forms['userForm']['fname'].value;
if (name == null || name == '') {
alert('Please enter your first name');
return false;
}
}
<label for="first-name">First Name: </label><br>
<input name="fname" type="text" /><br>
<button onclick="validate()">Submit Form</button>
I know this is a bit late, but I think I know what you're after. I've just done a similar thing myself, so I'll put it here incase it helps anyone.
I created a function so you can re-use it elsewhere along with an OK button to close the light box.
function customAlert(message = '') {
var alertBox = $(document.createElement('div'));
alertBox.html('<h3>'+message+'</h3><p><a class="featherlight-close">OK</a></p>');
$.featherlight(alertBox);
}
function validate() {
var name = document.forms['userForm']['fname'].value;
if (name == null || name == '') {
customAlert('Please enter your first name');
return false;
}
}
Basically, you cannot "return" it. What you can do is you can trigger a lightbox event when your conditions are match, like this:
function validate() {
var name = document.forms['userForm']['fname'].value;
if (name == null || name == '') {
$.featherlight($content, $configuration); // Lightbox for wrong validation
return false;
} else {
$.featherlight($content, $configuration); // Lightbox for successful validation
return true;
}
}
And of course, you will need to modify $content and $configuration variables as you want as explained here:
https://github.com/noelboss/featherlight/

Categories

Resources