Assign 0 if the value is null or empty in Jquery - javascript

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).

Related

javascript how to set null input equal to 0

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;

what is the issue in this javascript short circuit assignment

The following javascript code is getting giving undefined as the final output. But as far as I know the OR ' || ' operator will stop the evaluation as soon as it gets "true". But in this block of code it is trying to evaluate the remaining conditions even though it gets true on the first expression.
field = {
ipaddr: "0.0.0.0",
nodePresentInTopo: false
}
var bestName = field.ipaddr || (field.ip6addr && field.ip6addr != '::') ? field.ip6addr : undefined || field.sysid;
Here bestName always evalueavtes to undefined but why? As it is getting the value at field.ipaddr i.e 0.0.0.0
Please explain the logic.
In one word: operator precedence.
Yes, || short-circuits and doesn't evaluate the second half of the expression used as condition in the ternary operator.
field.ipaddr || (field.ip6addr && field.ip6addr != '::') ? .. : ..
Evaluates to:
'0.0.0.0' ? .. : ..
Which evaluates to true and then evaluates the true branch of the ternary operator:
field.ip6addr
If you want a different logical grouping, use parentheses:
field.ipaddr || (.. ? .. : ..);
I'm assuming you know that you've written field.ipaddr instead of fields.ipaddr. Probably for testing purposes. If the last part of the expression is your problem, write it like so:
(undefined || fields.sysid);
I don't think so is there any property with name ip6addr in current object?
var bestName = (field.ipaddr || (field.ip6addr && field.ip6addr != '::') ? field.ipaddr : undefined || field.sysid);
undefined
Either you should add ip6addr in current object or replace with appropriate property

Check for NaN, null and >=0 in one condition

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)

jQuery n times .append($('<td></td>')) = less than n columns?

var user = {};
var row = $('<tr></tr>')
.append($('<td></td>').text(user ? user.call_id : ''))
.append($('<td></td>').text(user ? user.phone_number : ''))
.append($('<td></td>').text(user ? user.dialed_number : ''))
.append($('<td></td>').html(user && user.admin ? '<span class="textgreen">admin</span>' : 'guest'))
.append($('<td></td>').append(_talking(user ? user.mute : 0)))
.append($('<td></td>').append($('<span></span>').addClass('timer').text(user ? user.duration : '')))
.append($('<td></td>').addClass('nowrap').append(_userButtons(user)))
;
alert( row.find('td').size() ); // = does NOT always alert 7, but a smaller value
Why is that so?
At the moment, user.dialed_number is undefined, therefore the missing column is the third one. And it doesn't matter how much I repeat that column, the result is always 6 in my project.
** UPDATE **
Here is a simplified jsfiddle showing the problem; it should output 7, but it shows 4
AHA!
$('<td></td>').text(undefined)
is the same as
$('<td></td>').text()
Which as per the jquery document for .text (look at the top right of the doc) it returns the text inside the element. Then you append that text (which is an empty string) to the <tr>. And that is why the <td> is not appended
Simple fix:
$('<td></td>').text((true ? undefined : 'false') || '') // oops should be ||
will do an empty string when the first part can be coerced to null (like undefined, 0, null, '', and 0.0)
Proof of concept: JS Fiddle
If any one of the expressions passed to .text() evaluates to null or undefined, the call to .text() will return the text of the TD - which is nothing - instead of the jQuery collection representing the TD. So you'd append 6 TDs and a nothing.
You're checking that the user exists each time, but not checking if the property exists which is returning undefined and making your statement append the contents of the td (which is nothing) instead of the td itself.
If you change your tests to check for the property instead, it works:
Demo
In your jsfiddle, the reason it is only showing 4 is that the properties on user are not defined.
Look at this jsfiddle
Maybe your user properties are not defined?
I would strongly suggest you stop trying to be quite so clever and single-step each append and see what's happening, rather than trying to do it all in one line. For one thing, it probably isn't doing what you think it should be doing anyway the way you wrote it - each td is getting inserted INSIDE the previous one!
Try this way:
var row = $('<tr></tr>');
row.append($('<td></td>').text(user ? user.call_id : ''));
row.append($('<td></td>').text(user ? user.phone_number : ''));
row.append($('<td></td>').text(user ? user.dialed_number : ''));
row.append($('<td></td>').html(user && user.admin ? '<span class="textgreen">admin</span>' : 'guest'));
row.append($('<td></td>').append(_talking(user ? user.mute : 0)));
row.append($('<td></td>').append($('<span></span>').addClass('timer').text(user ? user.duration : '')));
row.append($('<td></td>').addClass('nowrap').append(_userButtons(user)));
alert( row.find('td').size() ); // = alerts 6 when it should be 7
Also, when I run your code even with your crazy syntax (after ensuring that all functions and variables are defined and exist) I get 7.
The script appends the cell to the previous cell, not the row. $.end() returns the selected object at the beginning of the chain, i.e.:
$('tr', this).append($('<td>').text(user ? user.call_id : ''))
.end().append($('<td>').text(user ? user.phone_number : ''))
.end().append($('<td>').text(user ? user.dialed_number : '')) //etc.
corrected version
function _talking() {
return $('<span>TalkingFn</span>');
}
function _userButtons() {
return $('<button>button1</button><button>button2</button>');
}
var user = {};
var row = $('<tr></tr>')
.append($('<td></td>').text(user.call_id ? user.call_id : '{calli_id}'))
.append($('<td></td>').text(user.phone_number ? user.phone_number : '{phone_number}'))
.append($('<td></td>').text(user.dialed_number ? user.dialed_number : '{dialed_number}'))
.append($('<td></td>').html(user && user.admin ? '<span class="textgreen">admin</span>' : 'guest'))
.append($('<td></td>').append(_talking(user.mute ? user.mute : 0)))
.append($('<td></td>').append($('<span></span>').addClass('timer').text(user.duration ? user.duration : '')))
.append($('<td></td>').addClass('nowrap').append(_userButtons(user)))
;
alert( row.find('td').size() ); // = alerts 6 when it should be 7
$('#foo > tbody').append(row);

Javascript, String: Getting a Javascript var as a string

Because using .toString() for null vars doesn't work, and I can't be checking each and every one of these in my particular application.
I know this is a stupidly simple problem with an answer that literally must be staring me in the face right now.
The non-concatenation route is to use the String() constructor:
var str = new String(myVar); // returns string object
var str = String(myVar); // returns string value
Of course, var str = "" + myVar; is shorter and easier. Be aware that all the methods here will transform a variable with a value of null into "null". If you want to get around that, you can use || to set a default when a variable's value is "falsey" like null:
var str = myVar || "";
Just so long as you know that 0 and false would also result in "" here.
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String
How about
var str = '' + someVar;
What about
var str = (variable || "");
//or
(variable || "").toString();
Of course you'll get this for false, undefined and so on, too, but it will be an empty string and not "null"
String(null) returns "null", which may cause problems if a form field's value is itself null. How about a simple wrapper function instead?
function toString(v) {
if(v == null || v == undefined) {
return "";
}
return String(v);
}
Only null, undefined, and empty strings should return the empty string. All other falsy values including the integer 0 will return something else. Some tests,
> toString(null)
""
> toString(undefined)
""
> toString(false)
"false"
> toString(0)
"0"
> toString(NaN)
"NaN"
> toString("")
""
How about ... ?
var theVarAsString = "" + oldVar;

Categories