Javascript Problem - dependent combos in Spring Boot

0

Look at the image below;

Thishappenswhenloadingthecomboofcategoriestoloadthecomboofsubcategories.

Whatisthegoal?

WhenselectingthecategorycomboitwillautomaticallyloadthesubcategorycombobecauseofaJavascriptfile,howeveritisgeneratinganerrorintheJavascriptfileonline55.

Line55ofmyJavaScriptfileisbelow;

ThisprojectisaboutSpringBoot,Iunderstandabitofspringboot,butIknowverylittleaboutJavaScript,Ikindofgotacodereadyandtriedtoadaptit.

HereisthecompleteJavaScriptcode;

varArm=Arm||{};Arm.ComboCategoria=(function(){functionComboCategoria(){this.combo=$('#categoria');this.emitter=$({});this.on=this.emitter.on.bind(this.emitter);}ComboCategoria.prototype.iniciar=function(){this.combo.on('change',onCategoriaAlterada.bind(this));}functiononCategoriaAlterada(){this.emitter.trigger('alterado',this.combo.val());}returnComboCategoria;}());Arm.ComboSubCategoria=(function(){functionComboSubCategoria(comboCategoria){this.comboCategoria=comboCategoria;this.combo=$('#subcategoria');this.imgloading=$('.js-img-loading');}ComboSubCategoria.prototype.iniciar=function(){reset.call(this);this.comboCategoria.on('alterado',onCategoriaAlterada.bind(this));}functiononCategoriaAlterada(evento,codigoCategoria){//console.log('codigodacategória',codigoCategoria);if(codigoCategoria){varresposta=$.ajax({url:this.combo.data('url'),method:'GET',contentType:'application/json',data:{'categoria':codigoCategoria},beforeSend:iniciarRequisicao.bind(this),complete:finalizarRequisicao.bind(this)});resposta.done(onBuscarSubCategoriasFinalizado.bind(this));}else{reset.call(this);}}functiononBuscarSubCategoriasFinalizado(subcategorias){varoptions=[];subcategorias.forEach(function(subcategoria){options.push('<optionvalue"' + subcategoria.codigo + '">' + subcategoria.nome + '</option>');
            });
            this.combo.html(options.join(''));
            this.combo.removeAttr('disabled');


            var codigoSubCategoriaSelecionada = this.inputHiddenSubCategoriaSelecionada.val();
            if (codigoSubCategoriaSelecionada) {
                this.combo.val(codigoSubCategoriaSelecionada);
            }

        }


        function reset() {
            this.combo.html('<option value="">Selecione a SubCategoria</option>');
            this.combo.val('');
            this.combo.attr('disabled', 'disabled');
    }

        function iniciarRequisicao() {
            reset.call(this);
            this.imgloading.show();
        }

        function finalizarRequisicao() {
            this.imgloading.hide(); 
        }

        return ComboSubCategoria;
}());

$(function(){

    var comboCategoria = new Arm.ComboCategoria();
    comboCategoria.iniciar();
    var comboSubCategoria = new Arm.ComboSubCategoria(comboCategoria);
    comboSubCategoria.iniciar(); 

});

I accept all the suggestions and beg for help.

Any questions left my repository down for review.

This is my repository CLICK HERE

    
asked by anonymous 14.06.2017 / 21:48

1 answer

0

I do not know Spring Boot so I'll leave an example in "pure JS". You can also see running here in codepen and here at Fiddle .

// By Sidon | 2017
// Fiddle version: https://jsfiddle.net/Sidon/6m1nf0zu/62/
$(document).ready(function(){

    $('#brand').change(function() {populateCar()});  
  
    var ford = ['Fiesta', 'Focus', 'Fusion', 'Taurus', 'Mustang'];
    var vw = ['Passat', 'Tiguan', 'Golf', 'Jetta', 'Up']
    var fiat = ['Punto', '500', '500 City', 'Panda', 'Doblô']
    var cars =  {'Ford': ford, 'Volks': vw, 'Fiat': fiat}
    var brands = ['Ford','Fiat', 'Volks']
    populateBrand()
  
  
    function populateBrand() {
        $("#brand").empty();
        $("#brand").append('<option value="" disabled selected>Select your option</option>');
        $.each(brands, function(v) {
            $('#brand')
                .append($("<option></option>")
                .attr("value", brands[v])
                .text(brands[v]));
        })
    }


    function populateCar(event) {
        brand = $("#brand option:selected" ).text();
        $("#car").empty();
        for (let [k, v] of Object.entries(cars)) {
            if(k==brand) {
                for (car in cars[brand]) {
                    var opt = document.createElement("option");
                     $('#car')
                         .append($("<option></option>")
                         .attr("value", cars[brand][car])
                         .text(cars[brand][car]));
                }
            };
        }
    }
 
});
body {
  margin-left: 30px;
}

.inline-inputs select {
    box-sizing: border-box;
    width: 420px;
    height: 100%;
    border-radius: 3px;
    display: block;
    padding: 5px 8px;
    width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><!--BySidon|2017Fiddleversion:https://jsfiddle.net/Sidon/6m1nf0zu/62/--><body><h1>Populateonedropdownbasedonselectioninanother.</h1><p>ChangethecontentsofdropdownCarbasedontheselectionindropdownBrandusingjavascript:</p><formclass="form-horizontal" onsubmit="return false;">
        <fieldset>
            <div id="brandContainer" class="control-group">
                <label class="control-label" for "brand">Brand:</label>
                <div class="controls inline-inputs">
                    <select required id="brand"></select>
                    <span class="help-inline"></span>
                </div>   
            </div>
          
            <div id="carContainer" class="control-group">
                <label class="control-label" for "car">Car:</label>
                <div class="controls inline-inputs">
                    <select required id="car"></select>
                    <span class="help-inline"></span>
                </div>   
            </div>
        </fieldset>
    </form>
</body>
    
14.06.2017 / 21:58