Show the corresponding dropdown when an option is selected

Viewed 49

How can I show a second drop down based on the value of the first dropdown option selected? There's several options in the first dropdown, I want to use the value of that to tie it to the second drop downs class.

The value in the first dropdown options is the same as the var-<?php echo $product_id; ?> class, there's several dropdowns like the second one

<select class="prod-select" name="product_cat">
<?php while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
    <option value="<?php echo get_the_id(); ?>"><?php echo get_the_title(); ?></option>
<?php endwhile; ?>
</select>

<select class="var-<?php echo $product_id; ?>" name="product_var">
  <option value="4_week"><?php echo $variationName; ?></option>
</select>

This is my jquery, I'm not sure how to have a dynamic class name.

$('.prod-select').on('change', function() {
  $('.var-select').hide();
  $(this.value).toggle();
});
1 Answers

You can use $('select[class*="var-"]').. to hide all select and then use $(".var-" + this.value).. to show respective select-box.

Demo Code :

$('select[class*="var-"]').hide();
$('.prod-select').on('change', function() {
  $('select[class*="var-"]').hide(); //hide all select
  $(".var-" + this.value).show(); //show 
});
$('.prod-select').trigger('change') //trigger on page load
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="prod-select" name="product_cat">
  <option value="1">
    A
  </option>
  <option value="2">
    B
  </option>
</select>

<select class="var-1" name="product_var">
  <option value="">
    var 1
  </option>
</select>
<select class="var-2" name="product_var">
  <option value="">
    var 2
  </option>
</select>

Related