Search code examples
jqueryradio-button

Jquery - Setting text inside the closest span class after checking radio


I'm trying to add the value a user has checked from a radio and have it displayed in a span with the class 'user-set' with the corresponding header. The problem is when it displays the value, it displays it on all the headers with the span classes that have 'user-set'.

Here's an example: http://jsfiddle.net/fPWY3/

<div class='accordion'>
  <div class='heading'>
     <img src=''> heading <span class='f12'>info</span> <span class='user-set'></span>
  </div>
  <div class='items'>
     <input type='radio' class='next' name='theName' id='theName1'><label for='theName1'>thisIsMyValue 1</label>
  </div>
  <div class='items'>
     <input type='radio' class='next' name='theName' id='theName2'><label for='theName2'>thisIsMyValue 2</label>
  </div>

  <div class='heading'>
     <img src=''> heading 2<span class='f12'>info</span> <span class='user-set'></span>
  </div>
  <div class='items'>
     <input type='radio' class='next' name='theName2' id='theName3'><label for='theName3'>thisIsMyValue 3</label>
  </div>
  <div class='items'>
     <input type='radio' class='next' name='theName2' id='theName4'><label for='theName4'>thisIsMyValue 4</label>
  </div>
</div>

How can I do it so if I click on 'thisIsMyValue 3', the value will be displayed on the span with the class user-set from heading 2 only?


Solution

  • Use .prevAll() and .first().

    $(this).parent().prevAll('.heading').first().find('.user-set').text(val);
    

    Here is jsfiddle. http://jsfiddle.net/fPWY3/2/