Reputation: 1339
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
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:
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";
}
}
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
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