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

Asked

Viewed 914 times

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 you need a function in jquery that hides or shows the Divs according to the selection, ex:

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 make an if for each selected value.

EDITED I put together a gambit that worked, but I believe there’s a better way to make 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();
        });
});

1 answer

1


Using a loop for() 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>
<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">a</div>
<div id="2">b</div>
<div id="3">c</div>
<div id="4">d</div>

  • 1

    Perfect, Brigadão!

  • Thank you for being able to help

  • actually has a change to do, selects 2 and then 3, goes normal, but if select 1 back, he is not hiding the others

  • 1

    my gambiarra is to put $("#1,#2,#3,#4"). Hide(); at the beginning of . change

  • This, vc performs the closing dps the opening

Browser other questions tagged

You are not signed in. Login or sign up in order to post.