3
<input id="radio1" type="radio" name="rgroup" value="1" >
 <label for="radio1"><span><span></span></span>1</label>
<input id="radio2" type="radio" name="rgroup" value="2" >
 <label for="radio2"><span><span></span></span>1</label>

I have something like this and i want to add an image to the element which is checked using javaScript. How can i do it?

Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
user2417332
  • 49
  • 1
  • 2
  • 9

3 Answers3

6

Is it important for you to add a class for the radio which is checked? As you can do that simply with CSS:

#radio1:checked + label {
    color: #f00;
}

Demo

#radio1:checked + label:after {
    content: url(IMAGE_URL_HERE);
}

Demo 2 (With image embedded when you select the radio box)

Demo 3 (With tick image)

Ry-
  • 218,210
  • 55
  • 464
  • 476
Mr. Alien
  • 153,751
  • 34
  • 298
  • 278
0

First you need to find the checked radio:

function getCheckedRadioId(name) {
    var elements = document.getElementsByName(name);

    for (var i=0, len=elements.length; i<len; ++i)
        if (elements[i].checked) return elements[i].value;
}

Then add the image to the checked element.

var img = document.createElement("img");
img.src = "http://www.google.com/intl/en_com/images/logo_plain.png";

var src = getCheckedRadioId(rgroup);
src.appendChild(img);
src.parentNode.insertBefore(img, src.nextSibling);
Ry-
  • 218,210
  • 55
  • 464
  • 476
Norbert Pisz
  • 3,392
  • 3
  • 27
  • 42
0

Try this:

input[type="radio"]:checked + label {
    background-image: url("");
    background-repeat: no-repeat;
    background-position: center left; /* or center right */
}
Ry-
  • 218,210
  • 55
  • 464
  • 476
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231