Follow another example to answer the duplicate question: Change option of a select via javascript
<?php
if($_POST) {
if (isset($_POST['grupo'])) {
$grupo = $_POST['grupo'];
if (in_array($grupo, array('A',''))) {
$return = array(
array('id'=>'B','nome'=>'grupo B'),
array('id'=>'T','nome'=>'grupo T'),
);
}
if (in_array($grupo, array('B','B1','B2','B3'))) {
$return = array(
array('id'=>'T1','nome'=>'Opção 1 grupo B'),
array('id'=>'T2','nome'=>'Opção 2 grupo B'),
array('id'=>'T3','nome'=>'Opção 3 grupo B'),
);
}
if (in_array($grupo, array('T','T1','T2','T3'))) {
$return = array(
array('id'=>'B1','nome'=>'Opção 1 grupo T'),
array('id'=>'B2','nome'=>'Opção 2 grupo T'),
array('id'=>'B3','nome'=>'Opção 3 grupo T'),
);
}
echo json_encode($return);
exit();
}
}
?>
<a href="javascript:void(0)" id="post_x">Abrir opções</a>
<div id="select_a">Grupos: <select id="post_a"></select></div>
<div id="select_b">Grupos nivel 1:<select id="post_b"></select></div>
<div id="select_c">Grupos nivel 2:<select id="post_c"></select></div>
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(function(){
$('#select_a,#select_b,#select_c').hide();
$('#post_x').on('click', function(){
var valor = 'A';
carregarDados('<?php echo $_SERVER["SCRIPT_NAME"]?>', valor, 'a');
if(valor == '') {
$('#select_a').hide();
} else {
$('#select_a').show();
}
});
$('#select_a select').on('change', function() {
var valor = $(this).val();
if(valor == '') {
$('#select_b').hide();
} else {
$('#select_b').show();
}
carregarDados('<?php echo $_SERVER["SCRIPT_NAME"]?>', valor, 'b');
});
$('#select_b select').on('change', function() {
var valor = $(this).val();
if(valor == '') {
$('#select_b').hide();
} else {
$('#select_b').show();
}
carregarDados('<?php echo $_SERVER["SCRIPT_NAME"]?>', valor, 'c');
$('#select_c').show();
});
$('#select_c select').on('change', function() {
var valor = $(this).val();
if(valor == '') {
$('#select_c').hide();
} else {
$('#select_c').show();
alert('Submeter form com valor: '+valor);
}
});
});
function carregarDados(url, grupo, id_select) {
var data = {
grupo:grupo
};
$.post(url,data,function(e) {
var options = [];
var default_option = '<option value="" selected>Selecione...</option>';
var grupo = jQuery.parseJSON(e);
for(var i in grupo){
options[i] = '<option value="' + grupo[i].id + '">'
+ grupo[i].nome +
'</option>';
}
var opc = options.join("\n");
var selects = [
default_option,
opc].join("");
$('#post_'+id_select).html(selects);
});
}
</script>
Perfect... it was just that I tried to put in more in 1 field and giving conflict what I’m doing wrong http://jsfiddle.net/fabioo7/z8n92c49/
– Fabio Henrique
@Fabiohenrique ok, 2 min and send another version.
– Sergio
@Fabiohenrique don’t duplicate code that way. It takes a lot of work to maintain. Here’s a version of what you want: http://jsfiddle.net/8jhL4ao4/ I’ll add to the answer too
– Sergio