a div appears depending on the selected select

4

I have a select, and depending on the choice of the same select, a form will be shown to insert a contact. I have to keep in mind that the first option of the select already has the form to be shown by default, that is, the user when the page opens appears the company form. I have 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>
    
asked by anonymous 15.07.2014 / 17:43

2 answers

5

The best solution is to give a class to these divs that have forms to select from. Then name the ID of each div to value of option in 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 you just need to do this, using pure JS: link

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: link

$("#id_tipo_contacto").on('change', function(){
    $('.formulario').hide();
    $('#' + this.value).show();
});
    
15.07.2014 / 17:50
2

If you have only two options, you can do this 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 @Sergio's answer is well complete

    
15.07.2014 / 17:53