JSFiddle - React, Tailwind, and code Playground

by Martin Murciego

HTML

<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css">
<p>pais<br/><select style="width:300px" id="pais"></select></p>
<p>ua<br/><select style="width:300px" id="ua"></select></p>
<p>unidad<br/><select style="width:300px" id="unidad"></select></p>
<p>rol<br/><select style="width:300px" id="rol"></select></p>
<p>categoria<br/><select style="width:300px" id="categoria"></select></p>

JavaScript

clear('categoria');

//Intialise first select
anidado('pais', 'pais');
//Setup Complete

//Initial setup
clear('ua');
clear('unidad');
clear('rol');
function anidado(selectorOrigen, selectorDestino) {
    id = selectorOrigen;
    //alert(id);
    destino = "#" + selectorDestino;
    valor = $('#' + id).find(":selected").val();

    $.ajax({
        method: "POST",
        url: "https://fiddle.jshell.net/echo/json/",
        data: { 
            json :  JSON.stringify({
                select : id,
                valor : valor,
                arr : [
                    {codigo: '1', descripcion: 'ONE' },
                    {codigo: '2', descripcion: 'TWO'},
                    {codigo: '3', descripcion: 'THREE'}
                ]})
        }
    })
    .done(function (msg) {       
        //obj = $.parseJSON(msg);
        obj = msg.arr;

        if (obj.length > 0) {
            //Clear the current options
            $(destino).empty();
            
            //Append the 'Select an ---' option
            //The option will be selected once all values are added
            $(destino).append('<option value="x">Select an ---</option>');

            //Add returned options
            $.each(obj, function (index) {                
                valor = obj[index].codigo;
                texto = obj[index].descripcion;

                $(destino).append('<option value=' + valor + '>' + texto + '</option>');
                $(destino).prop("readonly", false);
            });
            
            //Remove disabled attribute
            $(destino).prop("disabled", false);
            
            //Re-initalise select2 - without this it doesn't accept the changed values
            $(destino).select2();
            
            //Select the option with value x
            //Include .trigger("change") to trigger change even if necessary
            $(destino).val('x'); //.trigger("change"); 
            
        } else {
           ...