zazvorniki
zazvorniki

Reputation: 3602

jQuery finding just the closest class to show a div

I'm having a small issue with my toggling. I have a bunch of yes and no answers and based on if they click yes or no there are more questions that appear. This was working fine until I had to move some of the yes and no questions inside a question that has already been answered.

My html looks sort of like this

 <div class="form-group">
    <label for="authorCover">
        Are you amazing? (Optional)
    </label>
    <button class="btn btn-small btn-success coverBtn yesBtn">Yes</button>
    <button class="btn btn-small btn-danger coverBtn noBtn">No</button>
    <p class="clearix"></p>
    <div class="answYes">
      <label for="upload">
        Please Upload your amazing here!
      </label>
      <input type="file" class="form-control" name="upload" value="" />
    </div><!--.answYes-->
    <div class="answNo">


   <div class="form-group">
     <label for="authorCover">
        Are you awesome? (Optional)
     </label>
     <button class="btn btn-small btn-success coverBtn yesBtn">Yes</button>
     <button class="btn btn-small btn-danger coverBtn noBtn">No</button>
     <p class="clearix"></p>
     <div class="answYes">
       <label for="awesome">
        Please Upload your awesomeness here
       </label>
       <input type="file" class="form-control" name="awesome" value="" />
     </div><!--.answYes-->
     <div class="answNo">no</div>
   </div><!--.form-group-->
  </div><!--.answNo-->
</div><!--.form-group-->

and my jQuery looks like this

$('.yesBtn').on('click', function(){
  $(this).parent().find('.answYes').toggle();
  $(this).parent().find('.answNo').hide();
  return false;
});

$('.noBtn').on('click', function(){
  $(this).parent().find('.answNo').toggle();
  $(this).parent().find('.answYes').hide();
  return false;
});

To make it a bit more clear I made a jsFiddel http://jsfiddle.net/pusKM/

Any help would be awesome!

Upvotes: 2

Views: 2701

Answers (1)

j08691
j08691

Reputation: 207901

Try using .closest('.form-group') instead of .parent()

$('.yesBtn').on('click', function () {
    $(this).closest('.form-group').find('.answYes').toggle();
    $(this).closest('.form-group').find('.answNo').hide();
    return false;
});
$('.noBtn').on('click', function () {
    $(this).closest('.form-group').find('.answNo:first').toggle();
    $(this).closest('.form-group').find('.answYes').hide();
    return false;
});

jsFiddle example

Upvotes: 1

Related Questions