Skip to content Skip to sidebar Skip to footer

Set Of Radio Buttons In "javascript"

I have a set of three radio buttons connected with a set of three images - i.e. {image1, radioBtn1}, {image2, radioBtn2}, {image3, radioBtn3}. I'm trying to do the following: When

Solution 1:

You can do this really easily using the <label> tag. Just use the following syntax:

<label>
    <input type="radio"id="radioBtb1" name="subject"/>
    <img id="image1" src="../image/img3.png" height="150px"/>
</label>
<label>
    <input type="radio"id="radioBtb2" name="subject"/>
    <img id="image2" src="../image/img3.png" height="150px"/>
</label>
<label>
    <input type="radio"id="radioBtb3" name="subject"/>
    <img id="image3" src="../image/img3.png" height="150px"/>
</label>

That will automatically do exactly what you are looking for.

Solution 2:

If you still wanna do it with javascript you can do like this. I made it so you coukld see everything that happens.

Check this working fiddle

window.onload = function () {

    var image1 = document.getElementById('image1');
    var image2 = document.getElementById('image2');
    var image3 = document.getElementById('image3');

    image1.addEventListener('click',runmewhenclicked);
    image2.addEventListener('click',runmewhenclicked);
    image3.addEventListener('click',runmewhenclicked);  

};  

functionrunmewhenclicked() {   

    var id = this.id;

    if(id == "image1")
    {
       document.getElementById("radioBtb1").checked = true;
    }
    elseif(id == "image2")
    {
       document.getElementById("radioBtb2").checked = true;
    }
    elseif(id == "image3")
    {
       document.getElementById("radioBtb3").checked = true;
    }
};

Post a Comment for "Set Of Radio Buttons In "javascript""