I have javascript function that will calculate the value for "TOTAL" row and "Balance" column in the table. But if there are no input, the javascript will return NaN which is not a number error.
How to set if there are no input in the text box, javascript will interpret it as 0 so that I will not get NaN error.
As you can see, the textbox for pay(notes 50) column are empty. Then value for balance and total become NaN.
just use logical 'or' operator (see short-circuit evaluation),
parseInt('10') || 0; // give 10
parseInt('') || 0; // give 0
You can check whether the value is a number by isNaN() function and then perform summation.
use isNaN(), put it in an if statement, if true, set the variable to 0
if(isNaN(yourVar)) {
yourVar = 0;
}
Ternary operator will work just fine
yourVar = (isNaN(yourVar)) ? 0 : yourVar
So if you want to check if your textbox value is empty or not, you can use:
val = your_textbox_value == '' ? 0 : your_textbox_value
assign that object to it this will work fine
you_object = you_object == null ? "0" : you_object;
Related
I want to use a ternary operator for the below jQuery statement like if employee_salary is empty or null, I want to assign as 0 (zero). Otherwise, just assign the actual value.
jQuery('#employee_form #employee_salary').val(parseInt(selected_table_data['employee_salary']))
var employee_salary = selected_table_data['employee_salary'];
var salary_form_value = employeeSalary ? parseInt(employee_salary) : '0';
jQuery('#employee_form #employee_salary').val(salary_form_value);
// If you want to inline it, you could do the following:
jQuery('#employee_form #employee_salary').val(
selected_table_data['employee_salary']
? parseInt(selected_table_data['employee_salary']
: 0
);
Here is an example
const s1 = null;
console.log(s1 ? s1 : 'There was a null value');
const s2 = ''
console.log(s2 ? s2 : 'There was an empty string');
const s3 = 'value';
console.log(s3 ? s3 : 'There was no value');
You can use ternary operator simply.
selected_table_data['employee_salary']
? parseInt(selected_table_data['employee_salary'])
: 0
console.log('' || 0);
console.log(null || 0);
console.log(undefined || 0);
I suspect that parseInt was your attempt to make this work yourself (fair enough). I'm going to suggest you remove it and try simply
jQuery('#employee_form #employee_salary').val(selected_table_data['employee_salary'] || 0);
A simple solution for you.
jQuery('#employee_form #employee_salary').val(selected_table_data['employee_salary'] * 1)
Using || operator or just a simple ternary operator would work if its null, undefined or ''. But it won't work for a blank space like this one ' ' (since Boolean (' ') evaluates as true) which it's not good if you want to replace any empty string or blank spaces for zero. So I would suggest you to do something like this,
jQuery('#employee_form #employee_salary').val(parseInt(selected_table_data['employee_salary']) ? parseInt(selected_table_data['employee_salary']) : 0);
This will allow you not only check if null, undefined, empty string and white spaces but also will prevent NaN to be a value on your form (instead zero will take place).
I need to validate the user input where user can only enter the value not equal to but greater than 0 and smaller than stated value. My validation logic works if i provide certain object
{required:true, greaterThan: 1, smallerThan: 50}
Here, if i input the value 0, then it displays an error message saying, value should be greater than 1 but if in case, i provide the following object instead
{required:true, greaterThan: 0, smallerThan: 50}
and I input the value 0 then it does not display an error message saying value should be greater than 0
Here is my validation logic
if (fieldValue.smallerThan && value && parseInt(value, 10) > fieldValue.smallerThan) {
set(
errors,
key,
`${fieldValue.label} should be smaller than ${fieldValue.smallerThan}`,
)
}
if (fieldValue.greaterThan && value && parseInt(value, 10) < fieldValue.greaterThan) {
set(
errors,
key,
`${fieldValue.label} should be greator than ${fieldValue.greaterThan}`,
)
}
0 && any value
Will always result in false because 0 is considered as falsy value in javaScript
What You can do is
fieldValue.greaterThan >= 0 && ..
If you're just checking for existence of the greater than property in the fieldValue, which seems to be what you're doing, you might also considering editing your two checks to be:
if (fieldValue.smallerThan !== undefined && ...)
and
if (fieldValue.greaterThan !== undefined && ...)
In general, relying on the truthiness or falsiness of values gets you into trouble, and it's better to be explicit about what you are checking for.
always convert your inputs to an integer or float.
if(!(fieldValue.smallerThan < parseInt(value))){
...value must be smaller than 50
}
if(!(fieldValue.greaterThan > parseInt(value))){
...value must be greater than 0
}
This question already has answers here:
How do you check that a number is NaN in JavaScript?
(33 answers)
Closed 6 years ago.
Is there a best way to prevent NaN? I have number input field that whenever I clear the field, I get NaN.
_amount: function(e) {
var value = parseInt(e.target.value);
var newValue = (value === NaN ? 0 : value); // Thought this could work
},
<input type="number" value={this.state.amount} onChange={this_amount} />
Now in my render I have 400 - this.state.amount. The things is, when I clear the input field, amount state is null. How to prevent this? Is it possible that when I clear the field I get zero? Say I type in 3 then clear the field, NaN pops up.
Thanks
NaNis never equals to anything including NaN itself hence rely on Number.isNaN(value) method.
_amount: function(e) {
var value = parseInt(e.target.value);
var newValue = (isNaN(value) ? 0 : value);
//OR sorthand as `NaN` is falsey
var value = parseInt(e.target.value) || 0;
}
The necessity of an isNaN function
Unlike all other possible values in JavaScript, it is not possible to rely on the equality operators (== and ===) to determine whether a value is NaN or not, because both NaN == NaN and NaN === NaN evaluate to false. Hence, the necessity of an isNaN function.[Ref]
The shortest way I found was
var number = (yourVariable || 0)
Because NaN is a falsey value, this will return 0 whenever yourVariable is NaN.
A way to check, if a number is NaN or not is to use the isNaN function.
isNaN(yourVariable); // Returns true is yourVariable is NaN
Side note:
The above method can be used for multiple problems too. For example: getting a value from an array (wich may not exist) and getting a value from a 2d array.
Getting value from array:
yourArray[i] || 0
Where i is the id you want to access
Getting value from a 2D array:
(yourArray[i] || [])[j] || 0
Where i and j are the position of the element in the array
In the condition portion of the following ternary statement, does playlist.length equal playlist.length >= 1 ?
var playlist = ["video1", "video2", "video3", "video4", "video5"];
// some code here
alert ((playlist.length) ?
playlist.length + "video(s) remain in the playlist: " + playlist.join (", ") + "."
: "No videos remain in the playlist");
Likewise, in the following snippet of code, does ! playlist.length equal playlist.length === 0 ?
alert ((! playlist.length) ?
"No videos in the playlist."
: playlist.length + " video(s) remain in the playlist: " + playlist.join(", ") + ".");
This is the first time I've seen an example where the condition portion of a ternary or if statement does not include such a notation as === or >=. So I'm not sure how to interpret this.
0 is implicitly converted to false in boolean comparisons in JavaScript. So when the length is 0, that is false. Conversely, any other number is implicitly converted to true in boolean comparisons in JavaScript. So when the length is anything but 0 it is true.
An easy test is to use !! to see the "truthy" value
!!1 === true
!!0 === false
!!6 === true
The part to the left of the ? is simply evaluated for "truthiness". The value 0 is "falsy" so evaluates as false for the purposes of the test. Numeric values other than 0 are "truish" and therefore for this purpose evaluate to true.
All other behaviors of the ternary are the same.
The === and !== simply add the additional constraint that the L-value and R-value must also be the same type.
The two are very similar: !playlist.length and playlist.length === 0.
However, they are not exacty the same. In fact, here:
var playlist1 = [];
var playlist2 = {};
!playlist1.length // true
!playlist2.length // true
playlist1.length === 0 // true
playlist1.length === 0 // false
In that sense !playlist.length also can be used on all kinds of objects, not just arrays.
In any case, when using this on an array, it is a way to check if the array is empty, and works as you have suggested, the same as playlist.length === 0.
In javascript 0 equals false, and any other number value equals true, but if you use === it compare value types too.
I have a var a;
Its value can be NaN, null and any +ve/-ve number including 0.
I require a condition which filters out all the values of a such that only >=0 values yield a true in if condition.
What is the best possible way to achieve this, I do not wish to use 3 different conditions joined using ||
typeof x == "number" && x >= 0
This works as follows:
null -- typeof null == "object" so first part of expression returns false
NaN -- typeof NaN == "number" but NaN is not greater than, less than or equal to any number including itself so second part of expression returns false
number -- any other number greater than or equal to zero the expression returns true
Ohk ...But i actually found the ans ..
it is so Simple .
parseInt(null) = NaN.
So if(parseInt(a)>=0){} would do ...Yayyee
NaN is not >= 0, so the only exclusion you need to make is for null:
if (a !== null && a >= 0) {
...
}
This seems to work well:
if (parseFloat(x) === Math.sqrt(x*x))...
Test:
isPositive = function(x) { return parseFloat(x) === Math.sqrt(x*x) }
a = [null, +"xx", -100, 0, 100]
a.forEach(function(x) { console.log(x, isPositive(x))})
My best solution to filter those values out would be with 2 condition and it is like;
if(a!=undefined && a>=0){
console.log('My variable is filtered out.')
}
I am not sure but there is no single condition usage to make it.
I had the same problem some weeks ago, I solved it with:
if(~~Number(test1)>0) {
//...
}
http://jsfiddle.net/pT7pp/2/
Since you tagged jQuery, take a look at $.isNumeric()
if($.isNumeric(a) && a >= 0)