Why am I getting an undefined error from this jquery? - javascript

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>

Related

JSON fail and continue code

I am pulling json from an external website. I grab a string with this code from their JSON as I parse it:
breweryName = data.data[i].breweries[0].name;
The problem is that one of the entries in the JSON I receive does not have a value for breweries[0].name.
How Can I keep executing the code? Despite one bad entry? I tried this:
if(data.data[i].breweries[0].name === "undefined"){
breweryName = "N/A"
}
else{
breweryName = data.data[i].breweries[0].name;
}
That still fails
this first checks if there are breweries at given index i and also if there are nested elements, by checking for the size property; within the inner loop, it checks for the name property with typeof():
if(
typeof(data.data[i].breweries) !== 'undefined' &&
data.data[i].breweries.size > 0
){
/* traverse the individual entries */
data.data[i].breweries.forEach(function(v, i){
if(typeof(v.name) !== 'undefined'){
/* the element has a name property */
} else {
/* name property is absent */
}
});
}
next time please provide some sample data, that makes answering more easy.
because it might be array or object... which requires different treatment.
In JavaScript, use the typeof function
if (typeof data.data[i].breweries === "undefined" ||
typeof data.data[i].breweries[0] === "undefined" ||
typeof data.data[i].breweries[0].name === "undefined")
you may also want to include
if (data.data[i].breweries[0].name.trim() === "")
to check for names that are present, but empty.
A shortcut approach may work as well ...
breweryName = data.data[i].breweries[0].name || "N/A"

Javascript variable is null but goes in if-statement

I have a bit of a weird problem. I TRIED to create a jsfiddle but I don't get the same result so I'm sorry I can't share more of what I have.
var parent = id && Number(oldParent) !== 1 ? $('#main_container #item_' + itemId).parent().parent().prev() : null;
This is how I get the parent. It should be null when it isn't needed.
Later, I get this check in the same function:
if (parent && parent != null && !parent.hasClass('.main-group'));
{
console.log(parent == null);
var siblingCount = parent.next().children().length;
if (siblingCount === 0)
{
parent.removeClass('group');
parent.addClass('normal-item');
}
}
So, I check if parent is set (just in case), parent is not null and parent doesn't have the class main-group. This should work, at least I thought, but I get the error:
TypeError: parent is null
On this row:
var siblingCount = parent.next().children().length;
So, that's why I added the console log to see if parent is null. Guess what? The console.log says true. This means parent is equal to null, but it still goes IN the if-statement. I use && so it shouldn't go in the if statement because already one operation is false.
I had others look at it and they couldn't figure it out either.
There is a semicolan at the end which is making it to execute as the statement is terminated and next statement executes.
var parent = null;
if (parent && parent != null && !parent.hasClass('.main-group'));{
alert("Hello");
}
For Debin comment:
var parent = null;
if (parent != null); { alert("Vinoth") }
// The above one is equivalent:
if (parent != null) do nothing ;
alert ("hi");
JavaScript thinks that you have an empty statement and everything to right of it is treated as no longer belonging to the if condition and thus an independent one making it to execute.
You have a ";" at the end of this line
if (parent && parent != null && !parent.hasClass('.main-group'));
This is what is causing the problem.

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.

Checking textbox if it's empty in Javascript

I wrote a simple html file with a textbox and submit button, and it generates and document.write's a response dependant on what you submit. I want to have it generate a response saying to enter content if the box is empty. The textbox's id is chatinput, so I have the following the code in the beginning
var chatinput_box=document.getElementById('chatinput');
var chatinput=chatinput_box.value;
Then a have a conditional, although I can't get it to work correctly; I've tried
if(chatinput==""){}
if(chatinput.length=0){}
if(chatinput=null){}
and others but none have worked correctly. Does anyone have another idea?
It should be this:
var chatinput = document.getElementById("chatinput").value;
if (chatinput == "" || chatinput.length == 0 || chatinput == null)
{
// Invalid... Box is empty
}
Or shorthanded:
if (!document.getElementById("chatinput").value)
{
// Invalid... Box is empty
}
The = assigns a value whereas == checks whether the values are equal.
Just offering an alternative, not trying to steal thunder ...
Create an isEmpty function to reuse on a variety of items.
function isEmpty(val){
return ((val !== '') && (val !== undefined) && (val.length > 0) && (val !== null));
}
Then you can apply it to whatever element you want:
if(!isEmpty(chatinput)){
// hooray its got a value!
}
Not exactly original, its the concept stolen from PHP, but it comes in handy a lot.

jQuery - how to write a if promt checking for childNode.length, nextSibling and childNode.nodeType

I need some good examples of how to write a if-statement checking all my div's for specified number of childNodes.lenght and childNode.nodeType.
And in addition to be 100 percent sure i got the right <div> and its right node also check for the nextSibling.
I am pretty new to jQuery/javascript so i might struggle in the syntax but here is what i got so far:
var specifiedChildNodesLength = ...
var specifiedChildNodesType = ...
if( $('div').childNodes.length == specifiedChildNodesLength &&
$('div').childNodes.nodeType == specifiedChildNodesType) { do something }
Try this:
if (($('div').children().length == specifiedChildNodesLength) && ($('div').children().get(0).nodeType == specifiedChildNodesType)) {}

Categories

Resources