Adam
Adam

Reputation: 20892

Check if img src is empty using jQuery attr

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

Upvotes: 2

Views: 14902

Answers (4)

Amit Sharma
Amit Sharma

Reputation: 1212

@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...');
}

Upvotes: 3

Adil
Adil

Reputation: 148150

! 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') != '') 

Upvotes: 6

Chris Dixon
Chris Dixon

Reputation: 9167

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/

Upvotes: 4

scottlimmer
scottlimmer

Reputation: 2278

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

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

Upvotes: 15

Related Questions