Java script returning undefined - javascript

I'm using String operations on javascript, I'm novice in JS. Here is my code.
function updateCLOB(row) {
var attrStr = row.get('CLOB_DATA');
if (attrStr == null && attrStr == undefined) {
return row;
} else {
var res = attrStr.split('||');
for (i = 0; i < res.length; i++) {
print('RES'=res[i]);
var temp = res[i].split('/');
var column = temp[4];
var value = temp[12];
row.put('WORKODR_' + column, value);
print('WORKODR_' + column + ' is ' + value);
}
}
return row;
}
My Clob data would be like 212323/2/January/3/4/5/6/7/1/2/3/4/5sd/123/45/56||............
Now im getting "undefined" in the output.
WORKODR_undefined is undefined.
Please let me know what im missing.
I tried to print the "res" value by and its printing as
RES2
RES1
RES2
.
.
.
Its splitting on every character. Why is this happening?

This:
if(attrStr==null && attrStr==undefined){
Should be:
if(attrStr!=null && attrStr!=undefined){
I am assuming you want to make sure it is not null and not undefined the if condition you have could never be met it can't be null and undefined...

try using:
if(attrStr!=null && typeof(attrStr)!='undefined'){

I have found the issue, the issue lies in the ||. Since I called this JS from a java app, I think the escaping of pipe is mandotary.
I used
var res = attrStr.split('\|\|'); and voila it worked !

Instead of
if (attrStr == null && attrStr == undefined) {
try using
if (!attrStr) {
the condition will be valid for null, undefined and zero length strings.

Related

Ajax check value of data

I'm getting data as JSON response and each time one of my fields is empty and one has value so I need to make if statement to check which one has value and print that one.
So far I tried:
if(data.longtext_dec != ''){
var ress = data.longtext_dec;
} else {
var ress = data.text_dec;
}
and
if($.trim(data.longtext_dec) === '')
{
var ress = data.longtext_dec;
} else {
var ress = data.text_dec;
}
each time the code keeps printing longtext_dec or show both as null.
So I need help to get this right, the result of this ress I want to append it in my view (either this or that).
How can I fix this code?
UPDATE
network response tab:
product_id 15
specification_id 5
text_dec ddd
longtext_dec null
id 69
payload
{"product_id":"15","specification_id":"5","text_dec":"ddd","longtext_dec":null,"id":69}
Just use if (data.longtext_desc) it's a way to check if data variable evaluates to true. undefined, null, false, 0, an empty string evaluates to false.
var ress; // undefined
if (data.longtext_desc) {
ress = data.longtext_desc;
} else {
ress = data.text_dec;
}
Optionally use a ternary operator:
var ress = data.longtext_desc ? data.longtext_desc : data.text_dec;
There is a difference between empty string, null, undefined and boolean true/false. As shown in the JSON you want to check if the value from the response object is null. So just check
if( data.longtext_dec !== null )
Here is very well explained:
https://stackoverflow.com/a/27550756/3868104
Optional you can check for whatever you want for example:
if( data.longtext_dec !== "" )
and so on.
you can leverage javascript || operator as below
var res = data.longtext_dec || data.text_dec;
Try this :
var data = {"product_id":"15","specification_id":"5","text_dec":"ddd","longtext_dec":null,"id":69};
var ress;
(data.longtext_dec !== null) ? ress = data.longtext_dec : ress = data.text_dec;
console.log(ress);

How should I properly assign a key and value pair?

JavaScript newbie. My code is working BUT I'm still getting this alert:
should_properly_assign_key_and_value_pair, Expected 'string' to be
'object'.
Not sure how update current code to address this issue. Any advice? Thank you!
function transformFirstAndLast(array) {
var result = '';
for (var i = 0; i < array.length; i++) {
result = (array[0] + ": " + array[array.length-1]);
return result;
}
}
console.log(transformFirstAndLast(['Kevin','Bacon','Spacey']));//Kevin : 'Spacey'
Since it is expecting a key/value pair. Create a new object and set the data.
Change
result = (array[0] + ": " + array[array.length-1]);
to
var result = {};
result[array[0]] = array[array.length-1];
return result;
It's hard to understand what your code wants to do? The current code will always return the first element and the last element in the array with a ':' in middle, regardless how many other elements in the array. Is that your intention? If yes, I think you don't need to the loop, right? just return array[0] + ':' + array[arraly.length - 1] does the job for you..
If your intention is to concatenate the elements in the array, your code need to be revised.

logic error in javascript code

I am trying to write some logic that will check for the existence of a specific record in two tables.
If the row exists in either table, I want to return TRUE.
For table A, when the record is added to the table, the id field looks like "123".
For table B, the same record would have the id of "a123". However, the value i have to search for the record is "row_123".
This is what my code looks like right now :
var checkForDuplicates = function(row_id) {
return !!($('#existing_members').find('#' + row_id.replace('row_','')).length || $('#selected_users').find('#' + row_id.replace('row_','a').length) );
};
I want the function to return true if the record exists in either table.
However, this statement returns true in cases when it should be false.
What I've tried so Far
I've been playing around in the console to make sure that my logic is correct:
!!(1 || 0) //returns true
!!(0 || 0) //returns false
!!(0 || 1) //returns true
I'm also currently reviewing the replace statements to make sure the find() is being supplied the right strings.
But a second pair of eyes to confirm that my logic is correct would be appreciated.
Thanks
EDIT 1
The solution, using Max's suggestion would be:
var checkForDuplicates = function(row_id) {
var parts = row_id.split('_');
var tableB = '#a'+ parts[1];
var tableA = '#' + parts[1];
return !!($('#existing_members').find(tableA).length || $('#selected_users').find(tableB).length);
}
However, as Ankit points out, I just had a typo in my original code. So this would be my final answer / solution:
var checkForDuplicates(row_id) {
return !!( $('#existing_members').find('#' + row_id.replace('row_', '')).length || $('#selected_users').find('#' + row_id.replace('row_','a')).length);
}
Your code has a typo at the end of return statement
...'a').length)); //it returns object which always evaluates to true
it should be
...'a')).length);
DEMO
var checkforduplicates = function(row_id){
//row_id looks like "row_123"
return !!($('#tableA').find('#' + row_id.replace('row_','')).length || $('#tableB').find('#' + row_id.replace('row_','a')).length );
}
alert(checkforduplicates("row_123"));
<table id=tableA><tr><td id="123">123 ID</td></tr></table>
<table id=tableA><tr><td id="a13">a13 ID</td></tr></table>
Corrected few issues to make the code more efficient:
var checkforduplicates = function(row_id) {
var id = row_id.split('_')[1]; // [ 'row', '123']
return $('#'+id).length || $('#a'+id).length;
}
No need for !! as operator || produces boolean result (true or
false)
Used $('#'+id) as more efficient jQuery selector
Removed unnecessary find(..) call
Eliminated unnecessary parenthesis (which had an issue)
I want the function to return true if the record exists in either table.
var checkForDuplicates = function(row_id) {
row_id = row_id.substring(4); // 'row_123' -> '123'
var table_A_row_id = row_id;
var table_A_row_exists = $('#tableA').find('#' + table_A_row_id).length > 0;
var table_B_row_id = 'a' + row_id;
var table_B_row_exists = $('#tableB').find('#' + table_B_row_id).length > 0;
return table_A_row_exists || table_B_row_exists;
};
of course it is returning the opposite of the things you want, cause you are using !!.
! is used to negotiate the return value of the specific function/variable e.g.:
if(!var_x == false)
this example only works if var_x is true.
So please be aware to avoid !! ;)
Please use a single ! instead!

Javascript Error: Cannot Convert Object to Primitive Value

I'm receiving this error using the following javascript code:
function tempTest(evt) {
alert(evt.currentTarget.id);
ct = document.getElementById(evt.currentTarget.id);
rslt = document.getElementById('rslt');
var props;
for (var prop in ct) {
if (ct.hasOwnProperty(prop)) {
propVal = ct[prop];
var propDat = prop + ' = ' + propVal;
props += propDat + '<br/>';
}
}
rslt.innerHTML = props;
}
This one has me puzzled. Any ideas?
Not all the properties of a HTML element are primitives. for example, parent, childs etc are also HTML elements. You can't just use them as strings or numbers.
You need to add there a condition and use that property accordingly.
If the object in question is json, you can call JSON.stringify(thingThatIsJson) which will return a String. .toString() does not work on json.
This is a message to those of you dealing with something like req.body which will work in console.log() which is rather confusing since it may not otherwise behave like a String (like when you're trying to add it to another String).
(The OP:)
Just wanted to post the updated snippet for anyone who stumbles onto this post...
function tempTest(evt) {
alert(evt.currentTarget.id);
ct = document.getElementById(evt.currentTarget.id);
rslt = document.getElementById('rslt');
var props;
for (var prop in ct) {
if (ct.hasOwnProperty(prop)) {
var propVal = ct[prop];
props += prop + ' (' + typeof(prop) + ')' + ' = ';
if (typeof(ct[prop]) == 'string') {
propVal += ct[prop];
} else {
if (propVal != null && propVal.toString) {
props += propVal.toString();
} else {}
}
props += '<br/>';
}
}
rslt.innerHTML = props;
}
The problem lies with the propVal part of your code. Since that may not be converted into a string.

Way to check a bunch of parameters if they are set or not in JavaScript

So, this happens to me quite frequently, but here's my latest one:
var generic_error = function(title,msg){
if(!title){ title= 'Oops!'; }
if(!msg) { msg = 'Something must have gone wrong, but no worries we\'re working on it!'; }
$.fancybox(
{
content:'\
<div class="error_alert">\
<h2>'+title+'</h2>\
<p>'+msg+'\
</div>'
});
}
Is there a cleaner way to check all params like title and msg above and OR set them as optional OR define defaults in the function like how PHP does it for example? Sometimes i could have 10 options and if(!var){var='defaults'} x 10 is icky...
Slightly shorter but equivalent to what you're doing now is to use "||" AKA "or" AKA "the default operator".
title = title || 'Oops!';
msg = msg || 'Something must have gone wrong, but no worries we\'re working on it!';
I doubt you'll find anything considerably shorter and simpler than if(!title)title='DefaultTitle' for function arguments.
However, I'd even use the longer form to make it more explicit: if (title===null) title='DefaultTitle'.
Here is a related question with an answer, but I think it would just makes your code more complicated. How can I access local scope dynamically in javascript?
You could use ternary notation as recommended by this article but in a simpler form:
var n = null;
!title ? title = 'Oops' : n;
You've also got the arguments[] array which holds the arguments and could be used in a loop, something like this:
function test(one,two,three) {
i=0;
while(typeof(arguments[i]) != 'undefined') {
alert(arguments[i++]);
}
}
test(40,27,399);
switch (arguments.length) {
case 0: title = 'Oops';
case 1: message = 'Something must have gone wrong...';
}
Here's another approach. The argsOK function is a little complex, but calling it is easy.
//-----------------------------------------------------
/*
PURPOSE Ensures a function received all required arguments, no extra
arguments & (if so specified) no arguments are empty.
RETURNS True if the arguments validate, else false.
*/
function argsOk(
functionCallee , // Caller's callee object
allArgsRequired , // True = All arguments are required
emptyArgsAllowed // True = Empty arguments are allowed
){
var ok = true;
for (var i = 0; i < 1; ++i) {
var functionName = functionCallee.toString().split(' ')[1].split('(')[0];
var args = functionCallee.arguments;
var expectedArgCount = functionCallee.length;
var actualArgCount = args.length;
if ((allArgsRequired && actualArgCount < expectedArgCount) ||
(actualArgCount > expectedArgCount)) {
error("Function " + functionName + " expected " + expectedArgCount + " arguments, but received " + actualArgCount + ".");
ok = false;
break;
}
if (emptyArgsAllowed) {
break;
}
for (var j = 0; j < args.length; ++j) {
if (args[j] != null && args[j].length == 0) {
error("Function " + functionName + "() received an empty argument.");
ok = false;
break;
}
}
}
return ok;
}
Example of calling it (a one-liner, as you can see):
//------------------------------------------------
function image(item, name, better)
// PURPOSE Write a request for picture or photo
// ENTRY Init() has been called
{
if (!showingShortVersion()) {
var betterString = '';
if (better != null && better == true)
betterString = 'better ';
if (argsOk(arguments.callee, true, false))
write('<p class="request maintain">If you have ac­cess to a ' + betterString + item + ' of ' + name + ' that we could put on­line, please click here.</p>');
}
}
In general, especially in Javascript, clean != short.
Do not use if(!title){ title= 'Oops!'; } as a general solution, because e.g. 0 and empty string are falsy, too. Arguments that are not set, are undefined, so I prefer using
if (title === undefined) {
title= 'Oops!';
}
It may be more wordy to do so, but It will prevent unwanted side effects, and in my experience, Javascript generates a lot of unwanted side effects, if you try to use shortcuts.

Categories

Resources