Yatish
Yatish

Reputation: 37

jQuery - How to find the src of next image element

on image click i am trying to change the img src to another img src. The below code is not working.

        if($ (this).next().find('img').attr("src") === '/survey/selfserve/53e/170605/FemaleSelectedNew_w800.png') {

            $ ($ (this).next().find('img').attr("src")).attr('src','/survey/selfserve/53e/170605/FemaleNew_w800.png');
        }

What i want is to look for the next img and check for its src and then if it matches the one i am looking for i want to change it.

Below is the entire script.

$ ('img').click(function(){

    if($ (this).attr('src') === '/survey/selfserve/53e/170605/MaleNew_w800.png'){ 
        $ (this).attr('src','/survey/selfserve/53e/170605/MaleSelectedNew_w800.png');
        $ (this).attr('data-src','/survey/selfserve/53e/170605/MaleSelectedNew_w800.png');


        if($ (this).next().find('img').attr("src") === '/survey/selfserve/53e/170605/FemaleSelectedNew_w800.png') {

            $ ($ (this).next().find('img').attr("src")).attr('src','/survey/selfserve/53e/170605/FemaleNew_w800.png');
        }
        return;
    } 

    if($ (this).attr('src') === '/survey/selfserve/53e/170605/MaleSelectedNew_w800.png'){ 
        $ (this).attr('src','/survey/selfserve/53e/170605/MaleNew_w800.png');
        $ (this).attr('data-src','/survey/selfserve/53e/170605/MaleNew_w800.png');
        return;
    }       

    if($ (this).attr('src') === '/survey/selfserve/53e/170605/FemaleNew_w800.png'){ 
        $ (this).attr('src','/survey/selfserve/53e/170605/FemaleSelectedNew_w800.png');
        $ (this).attr('data-src','/survey/selfserve/53e/170605/FemaleSelectedNew_w800.png');

        if($ (this).next().find('img').attr("src") === '/survey/selfserve/53e/170605/MaleSelectedNew_w800.png') {
            $ ($ (this).next().find('img').attr("src")).attr('src','/survey/selfserve/53e/170605/MaleNew_w800.png');
        }           
        return;
    }   

    if($ (this).attr('src') === '/survey/selfserve/53e/170605/FemaleSelectedNew_w800.png'){ 
        $ (this).attr('src','/survey/selfserve/53e/170605/FemaleNew_w800.png');
        $ (this).attr('data-src','/survey/selfserve/53e/170605/FemaleNew_w800.png');
        return;
    }                          


});

Upvotes: 1

Views: 577

Answers (1)

Mujthaba Ibrahim
Mujthaba Ibrahim

Reputation: 208

Do some simple changes:

if ($(this).closest('img').attr("src") === '/survey/selfserve/53e/170605/FemaleSelectedNew_w800.png') {
    $(this).next('img').attr('src', '/survey/selfserve/53e/170605/FemaleNew_w800.png');
}

Upvotes: 1

Related Questions