How to handle getElementById return Null - javascript

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.

Related

How to read an expression that assigns a value that has && and || in javascript of qml?

This is an assignment that's really strange to me.
I have a PanelTextField component on qml that was done by another person.
PanelTextField {
text: devtype.linkedData !== undefined && (""+devtype.linkedData.value) || "<unavailable>"
}
This seems to be something that is done on all kinds of JavaScript, but how can i read this?
You can read so: if devtype.linkedData not undefined then return cast devtype.linkedData.value as string else return "<unavailable>"
Test this:
var a;
var text = a !== undefined && (""+a) || "<unavailable>";
console.log(text); // RESULT: text = "<unavailable>"
a = "test";
text = a !== undefined && (""+a) || "<unavailable>";
console.log(text); // RESULT: text = "test"
&& and || have equal priority, so you should read it from left to right, it's the same as (.... && ....) || ....

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'])

Javascript: Uncaught TypeError: Cannot read property 'indexOf' of null

I'm populating a table with data - using fixed-data-table, which is a React.js component. However, that isn't so important at this stage.
The table has a search box where the issue stems from.
First, here's the interesting part of the code.
for (var index = 0; index < size; index++) {
if (!filterBy || filterBy == undefined) {
filteredIndexes.push(index);
}
else {
var backendInfo = this._dataList[index];
var userListMap = hostInfo.userList;
var userListArr = Object.values(userListMap);
function checkUsers(){
for (var key in userListArr) {
if (userListArr.hasOwnProperty(key) && userListArr[key].text.toLowerCase().indexOf(filterBy) !== -1) {
return true;
}
}
return false;
}
if (backendInfo.firstName.indexOf(filterBy) !== -1 || backendInfo.lastName.toLowerCase().indexOf(filterBy) !== -1 || backendInfo.countryOrigin.toLowerCase().indexOf(filterBy) !== -1
|| backendInfo.userListMap.indexOf(filterBy) !== -1) {
filteredIndexes.push(index);
}
}
}
This is rendered and the last part is throwing errors if you input something in the table, and a column returns null in the given cell.
The thing is, I can make the code work if I change the last part to ..
try {
if (backendInfo.firstName.indexOf(filterBy) !== -1 || backendInfo.lastName.toLowerCase().indexOf(filterBy) !== -1 || backendInfo.countryOrigin.toLowerCase().indexOf(filterBy) !== -1
|| backendInfo.userListMap.indexOf(filterBy) !== -1) {
filteredIndexes.push(index);
}
}
catch(err) {
console.log('Exception')
}
With the try/catch, it works 100% as intended and handles the indexOf returning null... But this can't be the way to properly handle it - I'm assuming this sort of exception handling is, well, supposed to be for rare exceptions, and shouldn't really be used on the front-end as much as the backend.
How do I handle the error in the title without using try/catch?
You are using indexOf, so make sure the values will not be undefined or null, You can solve it by putting the check on each values like this:
let {firstName, lastName, countryOrigin, userListMap} = backendInfo;
if ((firstName && firstName.indexOf(filterBy) !== -1)
|| (lastName && lastName.toLowerCase().indexOf(filterBy) !== -1)
|| (countryOrigin && countryOrigin.toLowerCase().indexOf(filterBy) !== -1)
|| (userListMap && userListMap.indexOf(filterBy) !== -1)) {
filteredIndexes.push(index);
}
or other way of solving this is, the default values you defined of these variables firstName, lastName, countryOrigin, userListMap, if they are array then it should be [], and if string then it should be ''.

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.

Why am I getting an undefined error from this jquery?

I'm trying to ensure there is always an image with a personal bio. There could be two images or none available to use (coming in from Xpath Parser feed). If no image is found in the XML, I want to load a default placeholder. Console tells me this line "Uncaught TypeError: Cannot read property 'indexOf' of undefined". I've tried many things to fix it but not having any luck. Any advise is appreciated.
if ($('.a_class').attr('src').indexOf('jpg') == -1
&& $('.b_class').attr('src').indexOf('jpg') == -1) {
$('.a_class').attr('src', '/folder/default_img.JPG');
}
First off, running the same jQuery selector multiple times is expensive. In my experience, saving the selector makes the Javascript visibly more responsive:
var aClass = $('.a_class');
var bClass = $('.b_class');
According to jQuery's attr(attributeName) documentation, it can return undefined if the attribute is not set, so you have a few things to check in your if condition. I'd also cache the result of attr(attributeName) in a variable:
var aClassSrc = aClass.attr('src');
var bClassSrc = aClass.attr('src');
This should finally work:
if ((typeof aClassSrc === "undefined" || aClassSrc.indexOf('jpg') == -1)
&& (typeof bClassSrc === "undefined" || bClassSrc.indexOf('jpg') == -1)) {
aClass.attr('src', '/folder/default_img.JPG');
}
Note that we're assuming a_class and b_class exist somewhere in the part of the DOM you're searching, and they exist once. If they don't exist, the attr(attributeName) calls won't do anything without warning. Additionally, if there are multiple a_class or b_class elements, the attr call that sets the "src" tag will set it for every a_class element. Make sure you are OK with this.
I used javaJake's answer as the foundation to write the rest of the necessary logic to hopefully make this work completely (see below). The code does not invoke any errors in the console. However, I have discovered that something (in the CMS) is hard-coded to override the javascript I'm adding to the page so I don't actually know if this works yet. Unless you see something glaringly obvious wrong with the code, I guess there is no point in responding just yet. I am looking into what is doing the override and will update the post when I do. I want to thank everyone for their help, comments, and suggestions thus far.
<script>
var aClass = $('.a_class');
var bClass = $('.b_class');
var cId = $('#c_Id');
var aClassSrc = aClass.attr('src');
var bClassSrc = bClass.attr('src');
// set default if nothing is returned in XML
if ((typeof aClassSrc === "undefined" || aClassSrc.indexOf('jpg') == -1) && (typeof bClassSrc === "undefined" || bClassSrc.indexOf('jpg') == -1)) {
cId.attr('src', '/folder/imagefield_default_images/bio_default_photo.JPG');
}
// if two images are returned, use aClass and hide bClass
else if ((typeof aClassSrc === "undefined" || aClassSrc.indexOf('jpg') >= 0) && (typeof bClassSrc === "undefined" || bClassSrc.indexOf('jpg') == 0))
$('.b_class').hide();
// if aClass is not preset, use bClass and hide aClass's broken image URL icon
else if ((typeof aClassSrc === "undefined" || aClassSrc.indexOf('jpg') >= -1) && (typeof bClassSrc === "undefined" || bClassSrc.indexOf('jpg') == 0))
$('.dm_image').hide();
</script>

Categories

Resources