gaurav
gaurav

Reputation: 1339

why is this code not work properly?

in this code when click on any radio button only image3.jpg show , in second click there is no change.

var a = document.getElementsByClassName('rbpic');

for (var i = 0 ; i<a.length ; i++) {
    a[i].addEventListener("click" , changepic );
}

function changepic() {
    var c = document.getElementById("image") ;

    for (var j=0 ; j<a.length ; j++)  {   
        var d = a[j].value ;

        if(d === "one") { 
            c.src = "image1.jpg";
        }
        else if (d === "two") { 
            c.src = "image2.jpg";
        }
        else if (d === "three") { 
            c.src = "image3.jpg";
        }
    }
}

Upvotes: -1

Views: 46

Answers (2)

Hatchet
Hatchet

Reputation: 5428

Your problem lies in the changepic() function: You're looping through every radio button and setting the corresponding image when any of the radio buttons changes.

My two solutions:

  1. Get rid of the loop and replace a[j].value with e.target.value:

    function changepic(e) {
        var c = document.getElementById("image");
        var d = e.target.value;
        if (d === "one") {
            c.src = "image1.jpg";
        } else if (d === "two") {
            c.src = "image2.jpg";
        } else if (d === "three") {
            c.src = "image3.jpg";
        }
    }
    
  2. Loop through all of the radio buttons and see which one is checked:

    function changepic() {
        var c = document.getElementById("image");
        for (var j = 0; j < a.length; j++) {
            if (a[j].checked) {
                var d = a[j].value;
                if (d === "one") {
                    c.src = "image1.jpg";
                } else if (d === "two") {
                    c.src = "image2.jpg";
                } else if (d === "three") {
                    c.src = "image3.jpg";
                }
            }
        }
    }
    

Upvotes: 2

Noble Mushtak
Noble Mushtak

Reputation: 1784

To refer to the radio button that was clicked in the event handler, use this:

var a = document.getElementsByClassName('rbpic');

for (var i = 0 ; i<a.length ; i++) {
    a[i].addEventListener("click" , changepic );
}

//We declare c on the outside so we're not calling document.getElementById() on every single click:
var c = document.getElementById("image") ;
function changepic() {
    //Get the value of this radio button:
    var d = this.value ;
    //Execute the following as normal:
    if(d === "one") { 
        c.src = "image1.jpg";
    }
    else if (d === "two") { 
        c.src = "image2.jpg";
    }
    else if (d === "three") { 
        c.src = "image3.jpg";
    }
}

Upvotes: 1

Related Questions