mardi 25 juillet 2017

Targeting the nth element of certain class when nth checkbox is checked?

So I have a dynamically listed set of elements, each structured as follows:

<div class="under-item-description">
  <span class="under-compare-price">100</span><span class="under-price">50</span>
  <span class="under-compare-price-2">200</span><span class="under-price-2">100</span>
  <div class="under-quantity">
      <label class="under-quantity-button">
        <input type="radio" checked="checked" name="quantity-1" class="under-quantity-radio" value="1"/>
      </label>
      <label class="under-quantity-button">
        <input type="radio" name="quantity-2" class="under-quantity-radio" value="2"/>
      </label>
  </div>
</div>

The amount of times the .under-item-description div is shown on the page can change. Currently, it shows four times.

What I am trying to do is when a user clicks on the first checkbox (name="quantity-1") in any given .under-item-description div, that div's .under-compare-price and .under-price shows, while .under-compare-price-2 and .under-price-2 are hidden.

If the second checkbox (name="quantity-2") is clicked, then .under-compare-price-2 and .under-price-2 are shown while .under-compare-price and .under-price are hidden, only in that .under-item-description div.

Here's my JS:

$('.under-quantity-button').click(function(){
  $('.under-quantity-radio').each(function(){
    if($(this).is(':checked')){
        $('.under-compare-price:eq('+$(this).parents('.under-item-description').index()+'), .under-price:eq('+$(this).parents('.under-item-description').index()+')').show();
        $('.under-compare-price-2:eq('+$(this).parents('.under-item-description').index()+'), .under-price-2:eq('+$(this).parents('.under-item-description').index()+')').show();
    }
  });
});

However, it doesn't seem to function as I want. Regardless of which second checkbox is clicked, I have the prices appear on the 1st and 3rd elements. And it doesn't switch back when the first checkbox is clicked anywhere. Any help?




Aucun commentaire:

Enregistrer un commentaire