some random dude
some random dude

Reputation: 467

JS: Cannot read property of 'src' of Undefined

I'm trying to check all input boxes if there is an image tag next to it that contains a certain image location in it's src.

var productThumb = document.getElementsByTagName("img").src;
var inputs = document.getElementsByTagName("input");
for (var i = 0, max = inputs.length; i < max; i++) {
    imgSrc = productThumb[i];
    if (inputs[i].type === 'checkbox' && imgSrc.indexOf("/img/folder/1/") === 0 )
        inputs[i].checked = true;
}

When I run this code I get the error in the title. What is wrong? I'm new to javascript so I have no idea what I am doing wrong but I think it has to be something with var = productThumb and imgSrc = productThumb[i]. What is the correct way of declaring the variables?

Upvotes: 0

Views: 3538

Answers (4)

Christose
Christose

Reputation: 1

Alternatively, jQuery provides a simple solution.

This

var productThumb = document.getElementsByTagName("img").src;

var inputs = document.getElementsByTagName("input");

Would become this

$productThumb = $('#PARENTid').find('img')[0].src;
$inputs = $('#PARENTid').find('input')[0].src;

Now for additional compatibility, if multiple libraries in use( which they likely are )

jQuery(function($){                                                      
$productThumb = $('#PARENTid').find('img')[0].src;
$inputs = $('#PARENTid').find('input')[0].src;                                     
}); 

Upvotes: -1

Christose
Christose

Reputation: 1

I think the proper solution would be to simply add [0] in front of .src this will choose which img within the collection to reference.

Example.

var productThumb = document.getElementsByTagName("img")[0].src;

Upvotes: 0

Sasank Mukkamala
Sasank Mukkamala

Reputation: 1574

Your code should be like this:

var productThumb = document.getElementsByTagName("img");
var inputs = document.getElementsByTagName("input");
for (var i = 0, max = inputs.length; i < max; i++) {
    imgSrc = productThumb[i].src;
    if (inputs[i].type === 'checkbox' && imgSrc.indexOf("/img/folder/1/") === 0 )
        inputs[i].checked = true;
}

This is because, in line 1, getElementsByTagName returns an array of img elements. And hence, getting src from an array of elements doesn't make sense.

Upvotes: 1

Hatchet
Hatchet

Reputation: 5428

getElementsByTagName returns an array-like structure (an HTMLCollection). Thus, productThumb is undefined because there's no src property in an HTMLCollection.

Simply remove .src from line 1 in your example, and add it at the end of line 4, and you should be good to go.

Upvotes: 1

Related Questions