Javascript Problem - Spring Boot Dependent Combos

Asked

Viewed 391 times

0

Look at the image below;

inserir a descrição da imagem aqui

This happens when loading the category combo to load the subcategory combo.

What is the goal?

When selecting the category combo it will load the subcategory combo automatically because of a Java script file, but is generating an error in the Javascript file on line 55.

The line 55 of my Javascript file is this below;

inserir a descrição da imagem aqui

This project is about Spring Boot, I understand a little about spring boot, but I know very little about Javascript, I kind of took a code ready and tried to adapt it.

Here is the complete Javascript code;

var Arm = Arm || {};

Arm.ComboCategoria  = (function () {

     function ComboCategoria(){
        this.combo = $('#categoria');
        this.emitter = $({});
        this.on = this.emitter.on.bind(this.emitter);
     }

     ComboCategoria.prototype.iniciar = function () {
        this.combo.on('change', onCategoriaAlterada.bind(this));
    }

     function onCategoriaAlterada() {
        this.emitter.trigger('alterado', this.combo.val());
    }
     return ComboCategoria;

}());

Arm.ComboSubCategoria = (function() {

        function ComboSubCategoria(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));
        }   

        function onCategoriaAlterada(evento, codigoCategoria) {
//          console.log('codigo da categória ', codigoCategoria);
            if(codigoCategoria){
                var resposta = $.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);
            }
        }

        function onBuscarSubCategoriasFinalizado(subcategorias) {
            var options = [];

            subcategorias.forEach(function(subcategoria){
                options.push('<option value"' + 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 suggestions and beg for help.

any doubt I left my repository down to analyze.

This is my repository CLICK HERE

1 answer

0

I don’t know Spring Boot so I’ll leave an example in "Pure JS". You can see running too here on codepen and here at the 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>
<!-- By Sidon | 2017
Fiddle version: https://jsfiddle.net/Sidon/6m1nf0zu/62/ -->
<body>
  <h1>Populate one dropdown based on selection in another.</h1>

    <p>Change the contents of dropdown Car based on the selection in dropdown Brand using javascript:</p>

    <form class="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>

  • you don’t need to know much about Spring Boot to solve this problem, which is really necessary and understand Javascript, even with your example could not help much, but still thank you

  • 1

    What problem you found, my example is in pure js, I have used in various contexts, always successfully. 'Study' my example, redo it in codepen (it’s free) or jsfidle, if you prefer, with your data and I’m sure you will be able.

  • The solution came from where you couldn’t even imagine! I made a small change in my project and it solved my problem, as I had mentioned before I did the project with Spring Boot and in it I use to show the information contained in the bank the Thymeleaf, what exactly I did was update Thymeleaf to the new version and include the Thymeleaf Extra artifact, and staying with the same Javascript code it worked. weird right?

Browser other questions tagged

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