In the following snippet, there is a dropdown menu with values 1 – 4. When a value is chosen, the corresponding number of textboxes "appear" by showing hidden divisions.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#elementreg").on("change", function() {
var val = $(this).val();
$('.types').hide(); //hide all
$(`#${val}`).show(); //show by matching the selected value
});
});
</script>
<label for="How Many Chips">How Many Chips?:</label>
<select class="medium" id="elementreg" name="amount">
<option value="" selected="selected"></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<div class="types" id="1">
<input name="First Chip ID">
</div>
<div class="types" id="2">
<input name="First Chip ID">
<input name="Second Chip ID">
</div>
<div class="types" id="3">
<input name="First Chip ID">
<input name="Second Chip ID">
<input name="Third Chip ID">
</div>
<div class="types" id="4">
<input name="First Chip ID">
<input name="Second Chip ID">
<input name="Third Chip ID">
<input name="Fourth Chip ID">
</div>
In this case, the code reveals the corresponding div based on the value chosen, while the other divs remain hidden. I would like it so that when a value is chosen from the dropdown menu, all divs less than or equal to the value chosen become shown. For example, if I choose the value 3, div with id=1, div with id=2, and div with id=3 become shown.
To attempt this, I tried changing the following line:
$(`#${val}`).show(); //show by matching the selected value
Into this:
$(`div[id <= ${val}]`).show(); //show all divs less than or equal to val
However, this only accomplished in breaking the feature. May I get help or suggestions on how I should be approaching this feature?
2
Answers
To achieve the desired behavior of showing all divs less than or equal to the selected value from the dropdown menu, you need to modify the JavaScript code accordingly. Instead of showing/hiding individual divs by their ID, you can use a loop to go through all the divs and check their IDs to determine whether they should be shown or hidden.
when you select a value from the dropdown, all divs with IDs less than or equal to the selected value will be shown, and the others will remain hidden. The loop goes from 1 to the selected value, and for each iteration, it shows the div with the corresponding ID.
You can use :lt() selector for achieving this . In your current structure you have common class for all divs i.e :
types
so use can add line$(`.types:lt(${val})`).show()
which will select all div less then the given value and show them.Demo Code :