Check if img src is empty using jQuery attr

13,952

Solution 1

Placing the ! at the start negates the $('img...') not the whole expression. Try:

if ($('img.photoPreview', this).attr('src') != '') {
    alert('empty src');
}

Solution 2

! operator will be evaluated before the result (boolean) returned from == operator and will be applied to object returned by selector instead of boolean returned by == operator.

Change

if(!$('img.photoPreview', this).attr('src') == '') 

To

if($('img.photoPreview', this).attr('src') != '') 

Solution 3

It's due to "src" being undefined. You should use this (it's more efficient than != ""):

if(!$('img.photoPreview', this).attr('src')) {
     alert('empty src...');
}

You can see this working here: http://jsfiddle.net/GKHvQ/

Solution 4

@adil & @scoot

if($('img.photoPreview', this).attr('src') != '') 

this condition says that if attribute src is not blank. But the condition would be to check if src attribute is ''.

better will be to use

if($('#photoPreview').attr('src') == '') {
 alert('empty src...');
}
Share:
13,952
Adam
Author by

Adam

Updated on June 26, 2022

Comments

  • Adam
    Adam almost 2 years

    I'm trying the following code:

                if(!$('img.photoPreview', this).attr('src') == '') {
                        alert('empty src...');
                }
    

    but it errors in the editor as not being completed correctly.

    Can someone advise what is wrong?

    Note: I'm trying to check - if not this image src is empty...

    thx