Select hide / show DIVs according to the selected value (jquery)

1

I have a select and some divs like this:

<select name="numerounidades" id="numerounidades">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>

Then I needed a function in jquery that hides or shows the divs according to the selection, eg:

Valor 1: só mostra o div id 1
Valor 2: mostra o div id 1 e 2
Valor 3: mostra o div id 1, 2 e 3
Valor 4: mostra o div id 1, 2, 3 e 4

Is there a way to build a simple jQuery function for this? The only way I know is to do an if for each selected value.

EDITED I put together a game that worked, but I think there is a better way to do it right?

<div id="1" class="d1 d2 d3 d4">1</div>
<div id="2" class="d2 d3 d4">2</div>
<div id="3" class="d3 d4">3</div>
<div id="4" class="d4">4</div>

$(document).ready(function() {
$('.d1').hide();
$('.d2').hide();
$('.d3').hide();
$('.d4').hide();
    $("#numerounidades").change(function(){
$('.d1').hide();
$('.d2').hide();
$('.d3').hide();
$('.d4').hide();
        var numero = 'd'+$(this).val();
        $('.'+numero).show();
        });
});
    
asked by anonymous 08.05.2018 / 17:42

1 answer

1

Using a for() loop makes it easy:

$("#1,#2,#3,#4").hide();
$("#numerounidades").change(function(){
    var num = parseInt($('#numerounidades option:selected').val());
    for (var i = 1; i <= num; i++) {
        $("#"+i).show();
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectname="numerounidades" id="numerounidades">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<div id="1">a</div>
<div id="2">b</div>
<div id="3">c</div>
<div id="4">d</div>
    
08.05.2018 / 17:57