how to check null in javaScript function? - javascript

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.

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

pattern match failure in if condition

Trying to optimise pattern matching code. Old code has few patterns which were matched against an Id coming from the callback data.
var Id = callbackData.Id
var pattern1 = /gen/g;
var pattern2 = /0--google/g;
var pattern3 = /mail/g;
var isPattern1 = pattern1.test(Id)
var isPattern2 = pattern2.test(Id)
var isPattern3 = pattern3.test(Id)
if(Id && Id !== 0 && !isPattern1 && !isPattern2 && !isPattern3)
{
//return statement
// function
} else {
//return statement
//function
}
To optimise it I have created a json file which consists the patterns. Pattern are being read from the json file and matched with the Id.
Json file : test.json
{
"PatternToSearch": {
"pattern1" : "gen",
"pattern2" : "^0--google",
"pattern3" : "mail"
}
}
var patternToMatch = require('test.json');
var patternArray = [];
Object.keys(patternToMatch.PatternToSearch).forEach(function (key) {
var value = PatternToMatch.PatternToSearch[key];
patternArray.push(value);
});
return Promise.all(patternArray);
.then(patternArrayResult => {
for (var val in patternArrayResult) {
var pattern = patternArrayResult[val];
var patternToCompare = new RegExp(pattern);
var isPattern = patternToCompare.test(Id);
}
})
I tried forEach as well but I am returning boolean value from the function and forEach doesn't return any value so I used for...in
not able to replicate this condition Id && Id !== 0 && !isPattern1 && !isPattern2 && !isPattern3. How to do it?
Tried
if(isPattern){
if(Id && Id !==0 && isPattern) {
// return statement
}
}
but this condition doesn't work when all the patterns don't match with Id. As I am this inside for loop only once this
condition will be true and other times false which takes the controller in else loop
How to replicate the condition? (Id && Id !== 0 && !isPattern1 && !isPattern2 && !isPattern3)
This is a job for some, which returns true if any item in an array causes a given function to return a truthy value:
return patternArray.some(v=>RegExp(v).test(Id));
And to include the value of Id in the test as well:
return Id && patternArray.some(v=>RegExp(v).test(Id));
You don't need to separately test Id !== 0 because a zero value will already be treated as falsy value, causing the && to short-circuit early. (So, Id && Id !== 0 will only ever produce 0 or true: execution flow cannot ever reach the condition Id !== 0 when that condition would be false, because the test Id for a zero value would have already terminated the && flow early.)

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 if some field does not exist in JavaScript

I have jQuery code like
for(var j in indivudvalbookdetails) {
if(indivudvalbookdetails[j]['status'] == "") {
...
}
}
Now there might be some items in the loop where status field won't exists, if there are such items the code in the if condition should work.
Try this:
var myElement = indivudvalbookdetails[j]['status'];
if (typeof(myElement) != 'undefined' && myElement != null)
{
// exists.
}
You can also try with JQuery like:
if ($('#elementId').length > 0) {
// exists.
}
Just check if its undefined:
if(typeof indivudvalbookdetails[j]['status'] === "undefined") {
...
Your code is comparing your variable to an empty string. But if this variable is not defined, it can’t compare it, so you can do :
if(indivudvalbookdetails[j]['status'] == undefined)
If the « status » var is defined but just empty you can do
if(indivudvalbookdetails[j]['status'] == null)
You check like this
if(!indivudvalbookdetails[j]['status'])

How to handle getElementById return Null

On our web application there are many pages. Some of them contain element "Ribbon.ListForm.Display.Manage.Workflows-Medium" while some pages not.
I would like to use same script to check against all pages. The script will hide the element "Ribbon.ListForm.Display.Manage", "Ribbon.ListForm.Display.Manage.Workflows-Medium" and "Ribbon.ListForm.Display.Manage.CheckOut-Large" if any.
function hideEdit() {
var edit = document.getElementById("Ribbon.ListForm.Display.Manage");
if (typeof edit !== "undefined" && edit.value == ''){edit.style.display = "none";};
var wf = document.getElementById("Ribbon.ListForm.Display.Manage.Workflows-Medium");
if (typeof wf !== "undefined" && wf.value == ''){wf.style.display = "none";};
var checkout = document.getElementById("Ribbon.ListForm.Display.Manage.CheckOut-Large");
if (typeof checkout !== "undefined" && checkout.value == ''){checkout.style.display = "none";};
}
The problem is when a page does not contain "Ribbon.ListForm.Display.Manage.Workflows-Medium" (the 2nd element) but contains "Ribbon.ListForm.Display.Manage.CheckOut-Large" (the 3rd element), the script will stop at in the middle with error [object is null or undefined]. Hence, 1st element is hided but 3rd element is not.
Could you please advice how to amend my script? Thank you.
Because getElementById() returns null if the element is not found.
element is a reference to an Element object, or null if an element
with the specified ID is not in the document.
You can just check for the truthy value instead of use the typeof test
if (edit && edit.value == ''){edit.style.display = "none";};
Demo: Fiddle
You can check like this for null element:
if (edit!=null && edit.value == '')
if (wf!=null && wf.value == '')
if (checkout!=null && checkout.value == '')
Even if the element is not existing in the page, the return type will be object and return value will be null.
so, you can check the null case also.
please see the modified code.
function hideEdit() {
var edit = document.getElementById("Ribbon.ListForm.Display.Manage");
if ( edit != null && typeof edit !== "undefined" && edit.value == ''){edit.style.display = "none";};
var wf = document.getElementById("Ribbon.ListForm.Display.Manage.Workflows-Medium");
if (wf != null && typeof wf !== "undefined" && wf.value == ''){wf.style.display = "none";}
var checkout = document.getElementById("Ribbon.ListForm.Display.Manage.CheckOut-Large");
if (checkout != null && typeof checkout !== "undefined" && checkout.value == ''){checkout.style.display = "none";}
}
thanks,
varun.
Since the question is tagged with jQuery:
$('#Ribbon\.ListForm\.Display\.Manage,#Ribbon\.ListForm\.Display\.Manage\.Workflows-Medium,#Ribbon\.ListForm\.Display\.Manage\.CheckOut-Large')
.filter(function() {
return this.value == '';
})
.hide();
First, it will select the elements you're interested in; then, it will hide those that match a simple filter based on value.

Categories

Resources