Gareth Gillman Gareth Gillman - 5 days ago 6
jQuery Question

jQuery hide item ony in a certain selector

I have the following html:

<li>
<select class="variation">
<option value="1">1</option>
<option value="2">2</option>
</select>
<p class="price"></p>
</li>


This is duplicated multiple times (list of products).

By default the first options price is displayed next to the dropdown, works fine, when i change the select it should change the price to the price of the selected option, that works fine BUT it doesn't hide just the other price for that product, it hides it for every product.

My JS:

$(".build-box-list li").each(function() {
$(".variation", this).on("change", function() {
$(".price").hide();
$("#" + this.value).show();
});
});


How do I hide just the price in the specific product li and not every product, I did try
$(".price", this).hide();
without success.

Thanks

Answer

From the code/html provided, the issue is this line:

$(".price").hide();

which does not have any context, so applies to all .price elements.

it hides it for every product

The event is on .variation, so to get the related .price you can use a number of methods, my preference is to go up to the parent and then back down (you could also use .siblings and .nextAll (or event .next if you're daring) if your html is unlikely to change in the future (which it probably will...)).

$(".build-box-list li").each(function() {
 $(".variation", this).on("change", function() {
  $(this).closest("li").find(".price").hide();
  $("#" + this.value).show();
 });
});

As an extra, you can remove the loop:

$(".build-box-list li .varation").on("change", function() {
  $(this).closest("li").find(".price").hide();
  $("#" + this.value).show();
});