Sunil Chavan
Sunil Chavan

Reputation: 3004

Replace radio buttons with images using JQuery

I have group of radio buttons which I want to replace with images when checked and unchecked.

<div id="answerOptions">
<input type="radio" name="answeroption" id="r1" value="radio1" checked=''checked'/>radio1<br/>
<input type="radio" name="answeroption" id="r2" value="radio2"/>radio2<br/>
</div>

I have two images 1. button_on.JPG for checked radio button and 2. button_off.JPG for not checked radio button. I want to accomplish following tasks 1. I want to replace radio buttons with these images. 2. On load of the page checked radio button should have correct image.

Note: Radio buttons are generated dynamically and their ids as well as value do change on each request.

I need the help using Jquery. Appritiate your inputs.

Upvotes: 1

Views: 14401

Answers (2)

jtfairbank
jtfairbank

Reputation: 2307

The following code does two things: 1. replaces the radio buttons on load. 2. Changes them when the images are clicked. I'm not going to garuntee that it is perfect for your situation, but it should be enough to get you started.

// on load
$(function() {
    // replace the checkboxes with the images
    $("input name='answeroption']").each(function() {
        if ($(this).attr('checked')) { // radio button is checked onload
            $(this).hide();
            $(this).after($("<img src='button_on.jpg' class='radioButtonImage' />"));
        } else { // radio button is not checked
            $(this).hide();
            $(this).after($("<img src='button_off.jpg'  class='radioButtonImage' />"));
        }
    });

    // setup click events to change the images
    $("input.radioButtonImage").click(function() {
        if($(this).attr('src') == 'button_on.jpg') { // its checked, so uncheck it
            $(this).attr('src', 'button_off.jpg');
            $(this).prev().attr('checked', 'false');
        } else { // its not checked, so check it
            $(this).attr('src', 'button_on.jpg');
            $(this).prev().attr('checked', 'true');
        }
    });
});

Upvotes: 2

Juan Ignacio
Juan Ignacio

Reputation: 3267

Don't reinvent the wheel, use a nice library for this:

http://uniformjs.com/

Upvotes: 4

Related Questions