Search code examples
javascriptjquerysubstr

Uncaught TypeError: Cannot read property 'substr' of undefined


The problem is, I have worked on the script jquery.min.js version 1.4. After had to upgrade to version 1.9.1, and there was a problem.

Uncaught TypeError: Can not read property 'substr' of undefined. 

Tell me what to do. This part of the code in which the error occurred.

var processCaption = function(settings){
                var nivoCaption = $('.nivo-caption', slider);
                if(vars.currentImage.attr('title') != ''){
                    var title = vars.currentImage.attr('title');
                    if(title.substr(0, 1) == '#') title = $(title).html();  

                    if(nivoCaption.css('display') == 'block'){
                        nivoCaption.find('p').fadeOut(settings.animSpeed, function(){
                            $(this).html(title);
                            $(this).fadeIn(settings.animSpeed);
                        });
                    } else {
                        nivoCaption.find('p').html(title);
                    }                   
                    nivoCaption.fadeIn(settings.animSpeed);
                } else {
                    nivoCaption.fadeOut(settings.animSpeed);
                }
            }

Solution

  • Try

    Soultion

    $.trim() will return empty string if it is undefined or it has only whitespace .

    if($.trim($('#abc').attr('title')) != ''){
    

    Problem

    if vars.currentImage.attr('title') doesn't have title attribute will return undefined not '' (empty string) . And you are checking for empty string so it goes inside the loop if it doesn't have title attribute

    So you get error because substr can only be applied to string.