Ajax check value of data - javascript

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

Related

How to prevent an empty string or null ("") value from being appended when pushing data into an array?

Here, there is a global variable. (An array type)
var obj = [];
I will add the values input to obj to the input.
function firstAddData()
{
var chozyintime = $('#ri_chozyinTime').val();
var chozyinArray = [chozyintime];
obj.push
(
{
"ri_chozyinTime" : chozyinArray,
}
);
}
The data entered in ri_chozyinTime will be stored as an array.
var chozyinArray = [chozyintime];
Now, add the value entered in "ri_chozyinTime".
cur.ri_chozyinTime.push(chozyintime); // cur is obj , chozyintime is input data
But this is a problem.
Because it also adds an empty string.
For example, when you look at the results,
ri_chozyinTime=[, , ]
What parts of my code should be modified to remove an empty string?
And I tried this, but it failed.
if(chozyintime != "" || chozyintime != null)
{
cur.ri_chozyinTime.push(chozyintime);
}
How can we solve this problem?
Your if condition is incorrect. When chozyintime = "", chozyintime != null is true; when chozyintime = null, chozyintime != "" is true.
So you should use && instead of ||:
if(chozyintime != "" && chozyintime != null)
{
cur.ri_chozyinTime.push(chozyintime);
}
Or you could just do this:
if(chozyintime)
{
cur.ri_chozyinTime.push(chozyintime);
}
This is probably because the value of chozyintime is undefined, which is neither "" nor null. A better guard would be:
if( chozyintime && chozyintime.length > 0 ) {
cur.ri_chozyinTime.push(chozyintime);
}
Just check if chozyintime is not empty, then add the values.
var obj = [];
function firstAddData()
{
var chozyintime = $('#ri_chozyinTime').val();
if (chozyintime.trim() != "") {
var chozyinArray = [chozyintime.trim()];
obj.push
(
{
"ri_chozyinTime" : chozyinArray,
}
);
}
}
$('#test').on('click', function(){
firstAddData();
console.log(obj)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="ri_chozyinTime">
<button id="test">push</button>

how to check null in javaScript function?

I want to check null and empty id in JavaScript function,but if syntax isn't work ?
var id = "<%=Request["Id"]%>";
if (id !== "")
if (id !== null)
{var id = "<%=new Guid(Request["ID"].ToString())%>";
window.location = "/Controller/Action.aspx?Id=" + id; }
With javascript,
If you are trying to test for not-null (any value that is not explicitly NULL) this should work for you:
if( myVar !== null ) {
// your code
}
If you are only interested to test for not-empty (null value, zero number, empty string etc..) then try:
if( !myVar ) {
// your code
}
If you want to test for if a variable is defined at all (which I believe is what you are trying to achieve) then you can do it like:
if( typeof myVar !== 'undefined' ) {
// your code
}
Please let me know if it works for you.
Read into binary logic:
var id = "<%=Request["Id"]%>";
if (id !== "" && id != null) {
var id = "<%=new Guid(Request["ID"].ToString())%>";
window.location = "/Controller/Action.aspx?Id=" + id;
}
Then again, var id = "<%=Request["Id"]%>"; will never be null, only empty string, so perhaps you can drop that check altogether.

Java script returning undefined

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.

string objects comparison always returning false

Here is the code that I am executing:
filterIssues: function(objectKey, text){
var view = this;
var keys = objectKey.split(".");
var attributeKey = keys[0];
var attributeName;
if (keys.length > 1){
attributeName = keys[1];
}
view.issues.each(function(issue){
var value = issue.get(attributeKey);
console.log(text);
if (value === undefined || value === null){
issue.trigger("hide");
return;
}
if (attributeName !== undefined){
value = value[attributeName];
}
if(value !== undefined){
var matchedText = value.substring(0, text.length - 1);
if ( matchedText === text){
issue.trigger("show");
console.log(value);
return;
}
}
issue.trigger("hide");
});
}
The matchedText == text always returns false.
This is what I get when I play around with the console:
> matchedText
"sande"
> text
"sande"
> typeof(text)
"string"
> typeof(matchedText)
"string"
> matchedText === text
false
> matchedText == text
false
I do realize that and === will always check if both the objects are the same and I have read
JavaScript equal operations anomalies and Javascript string equality.
Is there something wrong in the code that I am overlooking?
I think you are misusing the subString() method. If you use subString(), use the length without -1.
Well I eventually found out what was the problem. Thanks for your responses and I believe you might not have come across the answer for the lack of information.
The problem lied in the text value that I was passing to the function. The text contained a "" at the end and that's why comparison just did not work.

Meaning of == "" in javascript

Short questioion, I'm trying to understand this tutorial:
http://superdit.com/2011/02/09/jquery-memory-game/
Being new to Javascript I can't seem to find what the statement '== ""' means... I understand "==", but not the empty double quotes.
val == "" is a non-strict comparison to emtpy string. It will evaluate to true if val is empty, 0, false or [] (empty array):
var val = "";
console.log( val == "" ); // true
val = 0;
console.log( val == "" ); // true
val = false;
console.log( val == "" ); // true
val = [];
console.log( val == "" ); // true
You can use === to use strict comparison, fex:
val = 0;
console.log( val === "" ); // false
The ' == "" ' is a check for an empty string. It will be true when the string is empty, and false whenever there are some characters inside it.
A quick scan of the code (ctrl-F is your friend) quickly teaches you that the only time such a statement occurs in the code is here: if (imgopened == ""), another search taught me that imgopened is an evil (global) variable that is initialized to "" at the very top of the script, and every time some action/function is done with whatever value it was assigned.
I suspect it's a sort of card game, where two identical imgs need to be clicked, in which case this var will reference the image currently turned. If it's empty, then all imgs are facing down, and this var is empty: "".In other words:
if (imgopened == "")//=== if no card is turned
{
//do X, most likely: turn card
}
else
{
//do Y
}
This could've been written as
if (!imgopened)
//or
if (imgopened == false)//falsy, but somewhat confusing
//or
if (imgopened == 0)//!confusing, don't use
//or, my personal favorite
if (imgopened === '')

Categories

Resources