Question

Apologies in advance if this question has already been answered. I've searched through StackOverflow (as well as other sites) and any similar questions didn't seem to help me. Anyway, here is my dilemma:

I have a radio button that should control the image source of a javascript variable. Essentially, I want the image to change on click and have this occur in a way that requires the least amount of changes on the page. I realize this is likely a simple request but I am not that experienced in JavaScript and this has been driving me up a wall.

For some background info on how exactly my page is built:

Everything is contained in a Drupal module. The Drupal modules connect to our main server which hosts many webpages and applets. The individual applet is built with Javascript, jQuery, CSS+HTML.

I cannot share the code as it is work under an employer, but if you want me to elaborate further or give some pseduocode I can do that.

Thanks!

(P.S. - This is my first time posting to StackOverflow and I think I followed community guidelines but if there is any advice on how I could better pose my question (and any future ones) please drop me a line!)

Was it helpful?

Solution

You can do it the following way

HTML

 <img id="my_image" src="http://i.imgur.com/tL6nW.gif" alt="">

     <br>
<input class="radio" type="radio" name="radio" value="http://i.imgur.com/tL6nW.gif" checked>Image1<br>

<input class="radio" type="radio" name="radio" value="http://i.imgur.com/BfZ5f.gif">image2
</form>

JS

$('.radio').on({
    'click': function(){

        var image_url=$(this).val();
        $('#my_image').attr('src',image_url);
    }
});

Here is a JsFiddle

If you want to make it completely dynamic you can initialize the image element's default image at the page loading time too. The additional code will be something like this.

$(document).on('ready',function(){
 $('#my_image').attr('src','default.gif');
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top