wailing_stone
wailing_stone

Reputation: 173

Click event ignoring if/else in Jquery

I thought this would be simple: all I want is for JS to detect if the child img of the clicked link has a certain src attribute. If yes, do one thing. If no, do this other thing. But for some reason the click event is ignoring the if/else condition entirely. I can put any nonsense I want if the .children() selector and the event will still execute as if the condition is true. I don't know Jquery very well, so I'm at a loss. Any help would be appreciated.

$('.addcomp').click(function(){
                if($(this).children('img[src="add.png"]')){
                    $(this).parents("tr").find('.compcost').addClass('cost').end().find('td:last-child,td:nth-child(3)').addClass('addcompbg');
                    $(this).children("img").attr("src","forbidden.png");
                }
                else if ($(this).children('img[src="forbidden.png"]'))
                {$(this).parents("tr").find('.compcost').removeClass('cost').end().find('td:last-child,td:nth-child(3)').removeClass('addcompbg');
                    $(this).children("img").attr("src","add.png");
                    }
            });

Upvotes: 2

Views: 440

Answers (1)

João Silva
João Silva

Reputation: 91299

Use $(this).children('img[src="add.png"]').length instead. $() will always return a jQuery object, whether there is a match or not, hence it'll always be evaluated as true in the if.

Upvotes: 8

Related Questions