1

I am displaying a list that has a radio button inside each li. I want to select the radio button inside the li when the parent li is clicked.

List code:

$(".skin-complexion-list > li").click(function() {
  $(".skin-complexion-list > li > img + input[type=radio]").prop("checked", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="skin-complexion-list">
  <li>
    <img src="{{ 'icon-fair.png' | asset_url }}">
    Fair
    <input type="radio" name="skincomplexion" value="Fair" />
  </li>

  <li>
    <img src="{{ 'icon-medium.png' | asset_url }}">
    Medium
    <input type="radio" name="skincomplexion" value="Medium" />
  </li>

  <li>
    <img src="{{ 'icon-dark.png' | asset_url }}">
    Dark
    <input type="radio" name="skincomplexion" value="Dark" />
  </li>
</ul>

The jquery code above is not working. Any help is appreciated. Thanks

Calvin Nunes
  • 6,376
  • 4
  • 20
  • 48
redshot
  • 2,930
  • 3
  • 31
  • 68
  • Possible duplicate of [How to check a radio button with jQuery?](https://stackoverflow.com/questions/5665915/how-to-check-a-radio-button-with-jquery) – Laura May 15 '18 at 19:36

3 Answers3

4

You should be able to select the nested radio with

$(this).find('input:radio')

Ref. http://api.jquery.com/radio-selector/

Taplar
  • 24,788
  • 4
  • 22
  • 35
0

In most situations, I prefer Taplar's jQuery solution. If WCAG 2.0 accessibility is a factor for your website, I would recommend using the HTML non-js solution. Simply add a 'for' attribute to you label with a similar, yet unique, 'id' attribute to your radio button input. This also helps screen readers understand what your radio button means.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul class="skin-complexion-list">
  <li>
    <label for="skin1"><img src="{{ 'icon-fair.png' | asset_url }}">Fair</label>
    <input id="skin1" type="radio" name="skincomplexion" value="Fair" />
  </li>
  <li>
    <label for="skin2"><img src="{{ 'icon-medium.png' | asset_url }}">Medium</label>
    <input id="skin2" type="radio" name="skincomplexion" value="Medium" />
  </li>
  <li>
    <label for="skin3"><img src="{{ 'icon-dark.png' | asset_url }}">Dark</label>
    <input id="skin3" type="radio" name="skincomplexion" value="Dark" />
  </li>
</ul>
doppler
  • 795
  • 5
  • 9
0

You have to use the 'this' keyword inside the anonymous function.

$(".skin-complexion-list > li").click(function() {
  $(this).find('input[type=radio]').attr("checked", true);
});

the $(this) will refer to the clicked li element. and the find function will select the input:radio inside that clicked element.