show a div depending on the selected select

Asked

Viewed 7,318 times

4

I have a select, and depending on the choice of that same select, a form will be shown to insert a contact. I have to bear in mind that the first option of select already has the form to be shown by default, IE, the user when opening the page appears soon the form company. I got the following:

<select name="id_tipo_contacto" id="id_tipo_contacto">
    <option value="1">Contacto empresa</option>
    <option value="2">Contacto casamento</option>
</select>

<div id="empresa" style="display:none;">
      Mostra formulário empresa
</div>

<div id="casamento" style="display:none;">
      Mostra formulário casamento
</div>

2 answers

5


The best solution is to give a class to those Ivs that have forms to be able to select them. Then, name the ID from each div to value of option in the select.

Example:

<select name="id_tipo_contacto" id="id_tipo_contacto">
    <option value="empresa">Contacto empresa</option>
    <option value="casamento">Contacto casamento</option>
</select>
<div id="empresa" class="formulario">Mostra formulário empresa</div>
<div id="casamento" class="formulario" style="display:none;">Mostra formulário casamento</div>

So just need to do so, using pure JS: http://jsfiddle.net/c4hyM/

var select = document.getElementById("id_tipo_contacto");
var formularios = document.querySelectorAll('.formulario');

select.onchange = function () {
    for (var i = 0; i < formularios.length; i++) formularios[i].style.display = 'none';
    var divID = select.options[select.selectedIndex].value;
    var div = document.getElementById(divID);
    div.style.display = 'block';
};

If you want to use jQuery, you can use it like this: http://jsfiddle.net/c4hyM/1/

$("#id_tipo_contacto").on('change', function(){
    $('.formulario').hide();
    $('#' + this.value).show();
});
  • 1

    Thank you @Sergio!

2

If you only have two options, you can even do it in javascript:

alteraDiv = function (){
if($('#id_tipo_contacto').val() == 1){
    $("#empresa").show();
    $("#casamento").hide();
}

if($('#id_tipo_contacto').val() == 2){
    $("#empresa").hide();
    $("#casamento").show();
}

I leave here Jsfiddle

Dynamically the @Sergio response is quite complete

Browser other questions tagged

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