简体   繁体   中英

get div with specific class before form input

I have:

<div class="col-md-3 col-centered survey-kind-border">
    <a class="lv-item" href="#">
        <div class="media">
            <label for="no" class="pull-left">
                 <div class="survey_kind_choice">
                     1.5
                 </div>
                 <input checked="checked" class="survey_kind_input" id="no"  type="radio" value="no">
             </label>
             <div class="media-body">
                 <div class="lv-title">
                      No
                 </div>
                 <small class="lv-small">
                    I will Not
                 </small>
             </div>
        </div>
    </a>
</div>

<div class="col-md-3 col-centered ">
  <a class="lv-item" href="#">
      <div class="media">
          <label for="yes" class="pull-left">
            <div class="survey_kind_choice">
                2.5
            </div>
            <input class="survey_kind_input" id="yes" type="radio" value="yes">
          </label>
          <div class="media-body">
              <div class="lv-title">
                  Yes
              </div>
              <small class="lv-small">
                    I will
              </small>
          </div>
      </div>
  </a>
</div>

When someone goes to this page, one of the radio buttons will usually already be selected. If the button is selected, I want to grab the div that is associated with that form element and has the class "survey_kind_choice" and add a class to it. I am trying to do that with this code:

if($('.survey_kind_input').is(':checked')){
    alert('there is a checked element');
    $(this).prev('.survey_kind_choice').addClass('current_choice');
}

The alert is working, but I can't get the class to be added. What am I doing wrong and how do I fix it?

No if statement needed, just execute the selector on the checked input with:

$('.survey_kind_input:checked').prev('.survey_kind_choice').addClass('current_choice');

jsFiddle example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM