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
Related
I'm working on a calculator with vanilla JavaScript. I'm trying to make an if statement to find out whether the current result displayed has only one number left in the string. If this is true I want to make sure when the user clicks the delete button the current display returns to the default display instead of having no numbers in the string. I hope I explained this properly. How would I go about making this check.
const deleteNumber = () => {
let newDisplayedResult = currentResult[0].innerHTML.slice(0, -1);
if (firstNumber !== "" && currentOperator !== "") {
secondNumber = newDisplayedResult;
currentResult[0].innerHTML = newDisplayedResult;
} else {
firstNumber = newDisplayedResult;
currentResult[0].innerHTML = newDisplayedResult;
}
};
let re = new RegExp('^[0-9]$');
re.test(str)
or:
str.length === 1 && "0123456789".split("").includes(str)
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.
I have this JavaScript code
function checkTextField() {
var textVal = document.getElementById("textfield").value;
if (textVal == '', textfield.value.length <= 31)
{
alert('Wrong Key-Code. Key-Code must have 32 characters!');
}
else //Its all about how to decrypt a database file called ,,Salam Horia Allah,,!(good luck hackers)
{
{
var text = document.getElementById("textfield").value;
if (text ==
"3e6898f92134d05408dfed30b268d9d6",
"fa0f82cc02a6cdc35072ee5ce2b0c379",
"6a1df566fcaabca717aa1b81c3e0bd31",
"dc0beea186c5f5c2110bedbeccc5a7aa",
"1a317dbc4587268809b67179c391a5da9debb6261e3a3bcf7e6cd2b34356fc40",
"08a8c9750b3d184e6450b98fa90208bbd6c07171c0cce929bc52be1fdb44b09c",
"ac8ce3072f41269be4626539650bb1981c2939db0ffd576f240d06b0b7470c11",
"23a306626c5e9f83d8ce6012f9209fb8f3adcc1a098ffbfafd3c7965ed2c30a6",
"teBy%udu#uMuGyZe4uTyHeNa5yLy6avyTumypy8uHaGujytaWy",
"SezyDuXaquneguzuLatydy7e2ygu4y5e7uqe3e6uheVuVeSumu"
)
{
location.href = "http://79.115.70.31:8521/InWork/"
}
else {
alert("Wrong Key")
}
}
}
}
and here is what happen:
i have a textbox and a button,when i insert a key from if (text ==
"3e6898f92134d05408dfed30b268d9d6",
"fa0f82cc02a6cdc35072ee5ce2b0c379",
"6a1df566fcaabca717aa1b81c3e0bd31",
"dc0beea186c5f5c2110bedbeccc5a7aa",
And when someone press that button, I want that script to check if one of that keys are in text field, if is true the request will send to another page, if is not true, show an alert.
But my problem is, whatever I write in that textbox it send me to that page, also I got an alert if textbox have <31 characters.
The comma operator works inside of an if clause, but it takes the last value, not a logical OR, which is here required.
(An input returns always a string and if empty, the string length is zero. A check for emptiness and a check for a length which is smaller than a value is superfluous, because the length check includes a zero length as well.)
if (textVal == '' || textfield.value.length <= 31)
// ^^
Beside that, I suggest to use an array for the valid keys for checking and check only if the value is in the array, then proceed or give an alert.
Another point is to assign the value of the input only once and use it in the whole function with the variable. Do not use a mixed style with a variable and document.getElementById("textfield").value together.
function checkTextField() {
var keys = ["3e6898f92134d05408dfed30b268d9d6", "fa0f82cc02a6cdc35072ee5ce2b0c379", "6a1df566fcaabca717aa1b81c3e0bd31", "dc0beea186c5f5c2110bedbeccc5a7aa", "1a317dbc4587268809b67179c391a5da9debb6261e3a3bcf7e6cd2b34356fc40", "08a8c9750b3d184e6450b98fa90208bbd6c07171c0cce929bc52be1fdb44b09c", "ac8ce3072f41269be4626539650bb1981c2939db0ffd576f240d06b0b7470c11", "23a306626c5e9f83d8ce6012f9209fb8f3adcc1a098ffbfafd3c7965ed2c30a6", "teBy%udu#uMuGyZe4uTyHeNa5yLy6avyTumypy8uHaGujytaWy", "SezyDuXaquneguzuLatydy7e2ygu4y5e7uqe3e6uheVuVeSumu"],
text = document.getElementById("textfield").value;
if (keys.indexOf(text) !== -1) {
location.href = "http://79.115.70.31:8521/InWork/";
} else {
alert("Wrong Key");
}
}
Well you need to compare you tex with each key available so
function checkTextField() {
var textVal = document.getElementById("textfield").value;
var yourKeys =[ "3e6898f92134d05408dfed30b268d9d6",
"fa0f82cc02a6cdc35072ee5ce2b0c379",
"6a1df566fcaabca717aa1b81c3e0bd31",
"dc0beea186c5f5c2110bedbeccc5a7aa",
"1a317dbc4587268809b67179c391a5da9debb6261e3a3bcf7e6cd2b34356fc40",
"08a8c9750b3d184e6450b98fa90208bbd6c07171c0cce929bc52be1fdb44b09c",
"ac8ce3072f41269be4626539650bb1981c2939db0ffd576f240d06b0b7470c11",
"23a306626c5e9f83d8ce6012f9209fb8f3adcc1a098ffbfafd3c7965ed2c30a6",
"teBy%udu#uMuGyZe4uTyHeNa5yLy6avyTumypy8uHaGujytaWy",
"SezyDuXaquneguzuLatydy7e2ygu4y5e7uqe3e6uheVuVeSumu"];
if (textVal == '', textfield.value.length <= 31)
alert('Wrong Key-Code. Key-Code must have 32 characters!');
else {
var text = document.getElementById("textfield").value;
var i = yourKeys.length;
while(i--){
if(text == yourKeys[i] )
location.href = "http://79.115.70.31:8521/InWork/"
else
alert("Wrong Key")
}
}
}
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.
In this jsfiddle example, I have created a text-entry field that responds to the characters entered and appends a class to the parent <div> element for visual feedback based on whether the entry is expected, partial, or has an error.
In this case, the text field is for serial number entry; the field contents will eventually be sent to a dynamic table for building out an order. Because of this, the serial number must have an absolute value in the prefix (i.e: ABCDE in the example) and contain exactly 14 characters... I'm having difficulty coming up with a working code that will turn the text box green if the prefix is correct and remain green regardless of the remaining 9 characters (although they do need to be strictly numeric and end in a letter).
Additionally, I have a feeling there is a shorter and more elegant way to implement the script for the prefix check. Currently, I'm using:
if (el.value == "abcde" || el.value == "ABCDE") {
document.getElementById('serial').className = 'serial-entry success';
} else if (el.value == "a" || el.value == "ab" || el.value == "abc" || el.value == "abcd" || el.value == "A" || el.value == "AB" || el.value == "ABC" || el.value == "ABCD") {
document.getElementById('serial').className = 'serial-entry warning';
... where I know there's got to be a better way to write the expected ascending prefix values other than (el.value == "a" || el.value == "ab" ||... and so on. Using my current method, I would need to write half-a-billion variants of the el.value in order to satisfy all combinations.
Please be aware that I am not versed in JS; everything I know I've picked up from this site. It's the equivalent of moving to a foreign country and learning the language solely by eavesdropping on conversation - my grammar, syntax, and vocabulary are sparse, at best. In other words: feel free to humiliate me with sage-like wisdom.
--- EDIT: Answered! ---
Thanks to Felix Kling for the solution. I should have been more clear on where the state changes would occur, so I'll do so now and then include the code.
Rules:
1.) As the user enters the first letters of the prefix in correct order ("abcde"), the class of the text box should change to let the user know that they're on the right track, but not quite finished (partial).
2.) If the prefix is entered exact and we're agnostic of the following numbers ("123456789"), but they eventually do enter the correct prefix and a total of 14 characters, then the state (class) of the text box should toggle showing a success indicator.
3.) All other entries into the text box should be considered as erroneous, and an error class should be appended respectively.
4.) Lastly, if the user clears the text box of any string they entered, then the box should revert its class to the original state and not persist with any of the above classes.
Here is Felix's revised jfiddle.
And purely the JS:
function checkSerial(el) {
var value = el.value.toLowerCase();
var prefix = 'abcde';
var className = 'error'; // assume no match
if (!value) {
className = '';
}
else if (value.length === 14 &&
value.indexOf(prefix) === 0) { // match
className = 'success';
}
else if ((value.length >= prefix.length &&
value.indexOf(prefix) === 0) || // match
prefix.indexOf(value) === 0) { // partial match
className = 'warning';
}
document.getElementById('serial').className = 'serial-entry ' + className;
}
You could just use .indexOf and test that the string starts with the prefix:
document.getElementById('serial').className =
el.value.toLowerCase().indexOf('abcde') === 0 ?
'serial-entry success' :
'serial-entry warning';
For the three case, match, partial match, no match, you can check whether the input string is shorter than the prefix and apply the same logic, but vice versa:
var value = el.value.toLowerCase();
var prefix = 'abcde';
var className = 'error'; // assume no match
if (value.length >= prefix.length) {
if (value.indexOf(prefix) === 0) { // match
className = 'success';
}
}
else if (prefix.indexOf(value) === 0) { // partial match
className = 'warning'
}
document.getElementById('serial').className = 'serial-entry ' + className;
DEMO
suggesting to use RegEx to match the prefix as follows:
var val = el.value;
if(val.match(/\bABCDE/g)!=null) {
document.getElementById('serial').className = "serial-entry success";
} else {
document.getElementById('serial').className = "serial-entry error";
}
this way you can easily validate if the input is starting exactly with 'ABCDE'.
You can change the RegEx to suite your requirements.
Try this:
if(el.value.toLowerCase().indexOf('abcde') == 0 && el.value.length == 14)
document.getElementById('serial').className = "serial-entry success";
else
document.getElementById('serial').className = "serial-entry warning";