How to add msg to a variable that is undefined? - javascript

Hopefully I am asking the correct question. I want to add a msg that states "Please Enter Item weight" if the user clicks the button without inputting anything in the text field.
I tried multiple ways but can't seem to get it. A msg comes up saying "undefined" instead of what I want it to say/show.
if( typeof(weight) == 'undefined' || weight == null) {
msg = "<div id='error'>Please Enter Item Weight</div>";
}

You need to change weight definition to something like this:
var weight = parseInt(document.getElementById("weight").value || 0);
When you try to convert a string to a number using parseInt it will return NaN if you pass empty string (when there is no user input). So in this case simple fallback to 0 value || 0 can fix it.
Another option is to use + operator to cast to a number:
var weight = +document.getElementById("weight").value;
Demo: http://jsfiddle.net/AvjS5/1/

if( weight == 'undefined' || weight == null) {
msg = "<div id='error'>Please Enter Item Weight</div>";
}

What you might want to do is, use the isNaN function. When you try to do a parseInt on an invalid string, the value returned is NaN a.k.a Not a Number.
var weight = parseInt( document.getElementById("weight").value );
if(isNaN(weight)){
msg="<div>Hello</div>"
}
Fiddle here
Also, you haven't added logic to see if none of the option buttons were checked.

Related

How to ensure user-input data is a specific data type in JavaScript?

I have been working on some basic form validation in JavaScript. Currently, I have a simple HTML form that has three input fields - two requiring numerical input, and one requiring a string input. However, I am struggling to implement this.
const displayMessage = function (message) {
document.querySelector(".message").textContent = message;
};
const displayOtherMessage = function (message) {
document.querySelector(".message1").textContent = message;
};
document.querySelector(".check").addEventListener("click", function () {
const height = Number(document.querySelector(".height").value);
const weight = Number(document.querySelector(".weight").value);
const name = String(document.querySelector(".name").value);
if (!height && !weight && !name) {
displayMessage("Please enter a height, a weight and a name.");
} else if (!height || !weight || !name) {
displayMessage("Please enter a height, a weight and a name.");
} else if (height && weight && name) {
if (
typeof weight !== "number" ||
typeof height !== "number" ||
typeof name !== "string"
) {
displayOtherMessage(
"Height must be a number, weight must be a number and name must be a string."
);
}
displayMessage("");
alert(
`Thank you, ${name}! You said you weigh ${weight} kilograms and are ${height} metres tall.`
);
}
});
Here is what I am struggling with:
if (
typeof weight !== "number" ||
typeof height !== "number" ||
typeof name !== "string"
) {
displayOtherMessage(
"Height must be a number, weight must be a number and name must be a string."
);
}
When I try to submit, say, "John" in the second input field, displayMessage is shown. How do I make it such that displayOtherMessage is shown instead?
HTML here:
https://pastebin.com/E5Pm6Dku
Number() always returns a number and String() always returns a string, so those typeof checks don't do anything like what you seem to be hoping for.
If the string passed to Number() is an invalid number, it will return NaN. So you could try isNaN(weight) instead of typeof.
By the way, in the Node.js or browser console, you can experiment with this kind of thing directly, like do:
> var height = Number("john")
> height
NaN
> typeof height
"number"
> isNaN(height)
true
Try that also with a value that you want to be valid (like "10" or whatever).
Your code is a bit redundant in its checks. Such as, an <input> value will always be a string, so there is no need to check it's type, only that it isn't empty. Also, you should be more specific about what you need you user to do (which input is incorrect). You could simplify it to something like this:
const displayMessage = function (message) {
document.querySelector(".message").textContent = message;
};
document.querySelector(".check").addEventListener("click", function () {
let height = document.querySelector(".height").value,
name = document.querySelector(".name").value,
weight = document.querySelector(".weight").value;
if (!name) {
displayMessage("Please enter a name.");
} else if (!height || isNaN(Number(height))) {
displayMessage("Height must be a number.");
} else if (!weight || isNaN(Number(weight))) {
displayMessage("Weight must be a number.");
} else {
displayMessage(`Thank you, ${name}! You said you weigh ${weight} kilograms and are ${height} metres tall.`
);
}
});
https://jsfiddle.net/1L5qjg2o/3/
Also, consider using the keyup event on your inputs to do these checks. In my opinion, it's a much better user experience if you do validation and corrections as the user is inputting them, rather than waiting until the very end when they go to submit everything and then have to go backwards.

Checking input type in JS

I'm using the typeof command to make sure that only 1 of the 2 input fields of this temperature (Celsius to/from Fahrenheit) calculator is populated with data and it has to be a number. If the input is not a valid number or both fields are populated, the app will throw an error message.
The problem: nothing satisfies this condition - the errorMessage is always shown, even if I type in a valid number.
Is typeof the right solution to this problem? If it is, why is this code not working?
document.getElementById('temperature-form').addEventListener('submit', calculateResult);
function calculateResult(e) {
e.preventDefault();
const celsiusInput = document.getElementById('celsius');
const fahrenheitInput = document.getElementById('fahrenheit');
let resultOutput = document.getElementById('result');
// validate input data type and calculate result
if ((typeof celsiusInput === 'number') && (fahrenheitInput === null)) {
resultOutput.value = (celsiusInput.value * 1.8 + 32) + ' Fahrenheit';
} else if ((celsiusInput === null) && (typeof fahrenheitInput === 'number')) {
resultOutput.value = ((fahrenheitInput.value - 32)/1.8) + ' Celsius';
} else {
errorMessage('Please add a number in one of these fields');
}
}
Many thanks!
You could check the value properties of each input to see if they are numbers using the isNaN() function like so:
function calculateResult(e) {
e.preventDefault();
//Get the value of each input box
const celsiusValue = document.getElementById('celsius').value;
const fahrenheitValue = document.getElementById('fahrenheit').value;
//Get the result element
let resultOutput = document.getElementById('result');
// validate input data type and calculate result
if(!isNaN(celsiusValue) && (fahrenheitValue === null || fahrenheitValue === "")){
//Only celsiusValue has a valid number
resultOutput.value = (celsiusValue * 1.8 + 32) + ' Fahrenheit';
}else if(!isNaN(fahrenheitValue ) && (celsiusValue === null || celsiusValue === "")){
//Only fahrenheitValue has a valid number
resultOutput.value = ((fahrenheitValue - 32)/1.8) + ' Celsius';
}else if(!isNan(celsiusValue) && !isNan(fahrenheitValue )){
//Both contain a valid number
//Figure this one out as you didn't account for it
}else{
//Neither is a valid number
errorMessage('Please add a number in one of these fields');
}
}
Documentation of isNaN():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN
When doing const celsiusInput = document.getElementById('celsius') you're getting the DOM Element, not the value.
In order to obtain de value you'd have to check for the property value.
So you'd end up with something like this:
const celsiusInput = document.getElementById("celsius")
const celsiusValue = celsiusInput.value
Now if we do typeof celsiusValue we'll always get string, because text/number inputs always accept text (check input's type property for more info).
The proper way to check if there are numbers or letters is using Regular Expressions.
I'll leave a simple example to act as a starting point for you:
const celsiusInput = document.getElementById("celsius")
const celsiusValue = celsiusInput.value
if(/\D/.test(celsiusValue)) {
alert("There is something that's not a number in the Celsius input!")
}
First of by doing a comparison like this fahrenheitInput === null you're comparing a DOM element against the value null.
That will only evaluate to true if the DOM Element never existed.
Secondly the typeof method will always evaluate to a String on DOM element types, so again this will always be false.
To really get what you want you have to do a proper check
To check if both input fields are supplied, simply checking the length of the values will surface:
if(fahrenheitInput.length > 0 && celsiusInput.length > 0) //fail
If fahrenheitInput only is given:
if(!isNaN(Number(fahrenheitInput)) //convert
if celsiusInput only is given:
if(!isNaN(Number(celsiusInput)) //convert
Finally if all checks above don't check our, fail

I need help to design a 'Income' type textfield using JavaScript using conditions

For example a correct format will be 2,545.39.
The user must not to be able to enter anything except for what is show above.
The user must also enter in a valid input, for example a user can't enter in a value such as 002453.23, so they can't have 2 0's next to each other.
Use the below code:
var regex = /^\d+(\.\d{1,2})?$/i;
var key = $('textbox').val();
if ((key.match(regex) != null) || (parseInt(key) != 0)) {
$('textbox').val(key.replace(/^0+/, ''));
alert('legal');
}
else {
alert('illegal');
}

Check for number within a url using javascript?

I've a gallery within a website and each gallery image is represented by a url like so:
http://www.example.com/gallery/my-photos#10
http://www.example.com/gallery/my-photos#11
http://www.example.com/gallery/my-photos#12
.
.
.
.
.
I've created a conditional statement to prevent user from invalid url.
var galleryNum = window.location.hash.substring(1);
if( typeof(galleryNum) == "string" || typeof(galleryNum) == "NaN" ){
console.log('this is not a number');
}else if(typeof(galleryNum) == "number"){
console.log('this is a number');
}
However this doesn't work, the value I get from window.location.hash.substring(1) will always be a string regardless I enter number or a string.
if you want to get number, you should use:
parseInt(galleryNum,10)
if you want to check whether galleryNum is number or not, you can use:
isNaN(parseInt(galleryNum,10))
Try utilizing .test()
if( /\d/.test(galleryNum) ) {
// `Number`
} else {
// not `Number`
}
there is no "NaN" type. In fact, despite NaN standing for Not-a-Number, it actually is a number: typeof NaN === 'number'
You can however use isNaN() to test for NaN.
To test if the string returned from the URL can be cast to a number, use parseInt:
var galleryNum = parseInt(window.location.hash.substring(1),10);
if (typeof(galleryNum) === 'number' && !isNan(galleryNum)) {
// got a number here
}

Am I using the isNAN function in JavasScript correctly here?

I've got a form where the user inputs 3 values, which are then calculated. The outputs are displayed again within the form in some "readonly" output boxes. For each input, I want to validate if they are a number, if not, instead of the form showing "NaN" I want to display an error saying, "Please enter a number" (or something like that). Below is the code I am using, which is executed "onkeyup":
function checkforNumber()
{
if (isNaN(sInput || dInput || pInput) == true) {
alert("You entered an invalid character. Please reset the form.");
}
else {
return(false);
}
}
Am I using this function incorrectly? Is there something wrong with the syntax?
Thanks
if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput)) {
alert("You entered an invalid character. Please reset the form.");
}
also make sure that those 3 variables sInput, dInput and pInput are not strings but were obtained by using parseFloat or parseInt methods.
var sInput = parseFloat(document.getElementById('sinput').value);
var dInput = parseFloat(document.getElementById('dinput').value);
var pInput = parseFloat(document.getElementById('pinput').value);
if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput))
This is what I think you intended. You need to pass each value you want to test in to the isNaN function one at a time. Also note that you don't need the == true part, because isNaN returns true or false so the condition will evaluate to the return value.

Categories