How to find an HTML component in the DOM after using the .append () function?

3

I am making a request for my server with $.get of Jquery, and populating my table with the method below:

$.get(/*[[@{/empregados/salariosMinimos.json}]]*/ 'consultaEstadoSalario',         {uf : uf,data : data})
        .done(function(salarioestado){
                $("#tabela-salario-estado tbody tr").remove();
                for(var i in salarioestado){
                    if(salarioestado[i].dataFim == null){
                        salarioestado[i].dataFim = "";
                    }
                    var linhaTabela = $("<tr><td> " + formateDateJson(salarioestado[i].dataInicio) + "  </td> <td> " + formateDateJson(salarioestado[i].dataFim) +" </td><td class='text-right'> " + currencyFormat(salarioestado[i].valor)+" </td> " + "<td ><button id='btnSelecionar' class='btnSelecionar pull-right btn btn-xs btn-primary' type='submit' title='selecionar'><span class='glyphicon glyphicon-ok'></span></button></td>" + "</tr>");
                    $("#tabela-salario-estado").append(linhaTabela);

                }
        });

The problem is that when I run the .append() function it creates my view right there, but the button that I put in append with id = 'btnSelect' is not recognized in my DOM , that is, I can not find this id on the page and I can not do any js event with this button. So what would be the solution for him to recognize my button?

    
asked by anonymous 14.09.2015 / 14:06

1 answer

2

As you have not put where you are creating the button click event I will assume what I think is the problem.

The problem is as follows.

You are probably creating the click event of the button using either your ID or your CLASS. But if you do this it will only create this click event for elements that are already present on your page when .click () was called.

As you are creating elements dynamically this does not work. To work you should create a listener (or delegated event handler ) for your buttons.

Here's an example:

$('#pagina_onde_esta_meu_botao').on('click', '.btnSelecionar ', function(){
    console.log(this.value);
});

With this you have created an event on your page where your button will be created. this event listens to every click of any element that has the btnSelect class even though it is created after every DOM has already been loaded.

OBS Important

ID's are identifiers within a set (group) of elements. It is not good practice to create N buttons with the same ID. I advise you to put either an identifier that makes sense for your application or concatenate it with the index of for.

... id='btnSelecionar'" + i + " ...

For example.

    
14.09.2015 / 14:27