How to know if a dynamic <a> has been clicked in javascript

Asked

Viewed 123 times

2

need to know if a certain id of a <a> dynamically created was clicked.

 formatters: {

             return " <a href= '#'  class='btn btn-warning btnAlterarSolicitacao'  data-idSolicitacao='" + row.Id + "' id=btnFazerSolicitacaoEdicao" + row.Id +  "  data-colaboradorLatam='" + row.ColaboradorLatam + "' data-BP='" + row.BP + "' data-EmailColaborador='" + row.EmailColaborador + "' data-EspecieArquivo='" + row.EspecieArquivo + "' data-TipoArquivo='" + row.TipoArquivo + "' data-toggle='tooltip' data-placement='top' title='Editar' data-acao='Edit'data-row-id ='" + row.Id + "' > " +
                    "<span class='glyphicon glyphicon-edit'></span></a> &nbsp;"


            })

And that’s the javascript I was trying to get him.

The most I could get was to list them, I would like to know how to get this id that was clicked.

$(".text-left").find('*').each(function () {
    var id = $(this).attr("id");
    if (id !== undefined) {
       console.log(id);
    }

});

builder

function configurarControles() {

    var traducao = {
        infos: "Exibindo {{ctx.start}} até {{ctx.end}} de {{ctx.total}} registros", // 
        loading: "Carregando, isso pode levar alguns segundos...",
        noResults: "Não há dados para exibir",
        refresh: "Atualizar",
        search: "Pesquisar"
    }



        var controlarGrid = {
            ajax: true,
            url: urlListar,
            labels: traducao,
            statusMappins: {
                0: "Finalizado",
                1: "No prazo",
                2: "Atenção próximo ao prazo do SLA",
                3: "Prazo do SLA excedido"
            },
            searchSettings: {
                characters: 2
            },
            formatters: {

                "status": function (column, row) {
                    var totalDias = row.numeroDias;

                    if (totalDias >= 3) {
                        return " <button href= '#' class='btn btn-success'></button>";
                    } else if (totalDias < 3 && totalDias >= 0) {
                        return " <button href= '#' class='btn btn-warning'></button>";
                    } else if (totalDias < 0) {
                        return " <button href= '#' class='btn btn-danger'></button>";
                    }


                },

                //return diffDays;

                "data": function (column, row) {
                    return row.Day + "/" + row.Month + "/" + row.Year;

                },
                "DtSla": function (column, row) {
                    return row.dia + "/" + row.mes + "/" + row.ano;

                },  


                "acoes": function (column, row) {

                    return " <a href= '#' class='btn btn-warning'  data-toggle='tooltip' data-placement='top' title='Editar' data-acao='Edit'data-row-id ='" + row.Id + "' > " +
                        "<span class='glyphicon glyphicon-edit'></span></a> &nbsp;"
                        +
                        "<a href='#' class='btn btn-danger' data-toggle='tooltip' data-placement='top' title='Excluir'  data-acao='Delete' data-row-id ='" + row.Id + "' > " +
                        "<span class= 'glyphicon glyphicon-trash'></span></a>&nbsp "
                        +
                        "<a href='#' class='btn btn-info' data-toggle='tooltip' data-placement='top' title='Detalhar'  data-acao='Details' data-row-id ='" + row.Id + "' >" +
                        "<span class='glyphicon glyphicon-list'></span></a>";
                },
                "atualizar": function (column, row) {

                    return " <a href= '#' class='btn btn-warning'  data-toggle='tooltip' data-placement='top' title='Editar' data-acao='Edit'data-row-id ='" + row.Id + "' > " +
                        "<span class='glyphicon glyphicon-edit'></span></a> &nbsp;"
                        +

                        "<a href='#' class='btn btn-info' data-toggle='tooltip' data-placement='top' title='Detalhar'  data-acao='Details' data-row-id ='" + row.Id + "' >" +
                        "<span class='glyphicon glyphicon-list'></span></a>";
                },
                "AtualizarSolicitacoes": function (column, row) {
                    console.log(row);
                    return " <a href= '#'  class='btn btn-warning btnAlterarSolicitacao'  data-idSolicitacao='" + row.Id + "' id=btnFazerSolicitacaoEdicao" + row.Id +  "  data-colaboradorLatam='" + row.ColaboradorLatam + "' data-BP='" + row.BP + "' data-EmailColaborador='" + row.EmailColaborador + "' data-EspecieArquivo='" + row.EspecieArquivo + "' data-TipoArquivo='" + row.TipoArquivo + "' data-toggle='tooltip' data-placement='top' title='Editar' data-acao='Edit'data-row-id ='" + row.Id + "' > " +
                        "<span class='glyphicon glyphicon-edit'></span></a> &nbsp;"
                        +

                        "<a href='#' class='btn btn-info' data-toggle='tooltip' data-placement='top' title='Detalhar'  data-acao='Details' data-row-id ='" + row.Id + "' >" +
                        "<span class='glyphicon glyphicon-list'></span></a>";
                },

                "nomeSolicitante": function (column, row) {
                     return row.Solicitante.Nome;
                },
                //"DescricaoGAreaCliente": function (column, row) {

                //    return row.GAreaCliente.Descricao;
                //}
                "DescricaoUf": function (column, row) {
                   return row.Uf.Descricao;
                },
                "AnoOrcamentario": function (column, row) {
                    return row.DtRemessa.substring(6,10)
                }
            }
        }
        var grid = $("#gridDados").bootgrid(controlarGrid);
        //assim que carrega o bootgrid
        grid.on("loaded.rs.jquery.bootgrid", function () {

            $('[data-toggle="tooltip"]').tooltip();
            //pesquisa os botões de list, update e delete
            grid.find("a.btn").each(function (index, elemento) {



                var botaoDeAcao = $(elemento);
                //descobre de qual tipo é o botão
                var acao = botaoDeAcao.data("acao");

                //pega qual id do campo
                var idEntidade = botaoDeAcao.data("row-id");

                botaoDeAcao.on("click", function () {

                    //chamada modal para os demais botões
                    abrirModal(acao, idEntidade);

                });
            });
        });
        // chamada modal para os botões de create
        $("a.btn").click(function () {

            var acao = $(this).data("action");

            abrirModal(acao, null);
        });
    }

    function abrirModal(acao, parametro) {

        var url = "/{ctrl}/{acao}/{parametro}";

        url = url.replace("{ctrl}", controller);
        url = url.replace("{acao}", acao);

        if (parametro !== null) {

            url = url.replace("{parametro}", parametro);
        }
        else {
            url = url.replace("{parametro}", "");
        }

        $("#conteudoModal").load(url, function () {

            $("#minhaModal").modal('show');
        });

    }
  • If the a is created dynamically is a problem of delegating events as has appeared in countless questions around here.

  • As well as delegation problem?

  • The point is that click events and others are assigned to the elements that exist at the time. Those that are inserted later do not pick up this. The way to solve is with delegation. I already try to find the related questions to put here

1 answer

3


You can click for any attribute you have in the collection. For example, you can click for the class .btnAlterarSolicitacao, using the method .on() with delegation ($(document)):

$(document).on("click", ".btnAlterarSolicitacao", function(event){

   event.preventDefault();
   console.log($(this).attr("id")); // imprime o atributo id

});

In your specific case, it may be conflict of events with the class .btn. Try using another event, like:

$(document).on("mouseenter", "a[data-idsolicitacao]", function(){
   var id = $(this).attr("id");
   console.log(id);
});

The problem of mouseenter is that the button will be activated by simply passing the mouse over it. The recommended one was to change the events without the class .btn, because it is very generic and may conflict with other events click.

  • I believe this is the best solution, but this way nothing appears to me on the console and I’m doing exactly as you put

  • Try now with the changes.

  • Still no @sam

  • Weird then. You should take the click.

  • Yes, very strange, I don’t understand why

  • Well, I need to get which id clicked, so I can retrieve the necessary information, after this information I will send a request with this value recuprado

  • Not even putting an Alert inside the function appears?

  • 1

    with the mouseenter I believe it will work the way I need, thank you very much

Show 4 more comments

Browser other questions tagged

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