patricko
patricko

Reputation: 831

How do I target an image inside a specific span?

I'm building a multiple-choice questionnaire, using jQuery to toggle radio buttons on hover. I have a span for each possible answer, and inside that I have the radio button that I would like to swap the source out on hover.

Now these are images that I made, not actual radio buttons. I have two images, checked and unchecked, and I'm swapping the src when the user hovers.

So when the user hovers over the radio button itself OR the actual text next to the radio button, the button shows a dot.

Here is my span that contains the radio button AND the text (keep in mind I have 5 of these).

<span class='choice' id='A'><img src="images/radioUnchecked.png" width="20" height="21" class='radioButton'>A) Naked woman</span>

So how would I use jQuery to target the radio button when the user hovers over the text?

EDIT: Here is the jQuery I was using to toggle, but it only works when the user hovers over the image.

$('img.radioButton').hover(function () {
    this.src = 'images/radioChecked.png';
}, function () {
    this.src = 'images/radioUnchecked.png';
});

Upvotes: 0

Views: 369

Answers (1)

thecodeparadox
thecodeparadox

Reputation: 87073

$('span.choice').hover(function() {
   $('img.radioButton', this).attr('src', 'images/radioChecked.png')
}, function() {
   $('img.radioButton', this).attr('src', 'images/radioUnchecked.png')
});

If you have more element with class choice then you can try following:

$('span.choice').has('img.radioButton').hover(function() {
   $('img.radioButton', this).attr('src', 'images/radioChecked.png')
}, function() {
   $('img.radioButton', this).attr('src', 'images/radioUnchecked.png')
});

$('span.choice').has('img.radioButton') will detect only span that contains img.radioButton.

Upvotes: 5

Related Questions