How to return the dynamically inserted element id?

Asked

Viewed 175 times

1

How to return the id of an element inserted dynamically? I don’t know where I’m going wrong. When the elements are already on the page, it works normally, but it was enough to insert them dynamically to stop working.

if($("#_INSERIR_").length > 0)
{  
    var id_c = parseInt($("#_INSERIR_ p:last")[0].id.split("_")[1]);

    $("#novo_reg").click(function()
    {
        id_c ++;
        var html_new_reg = '<p id="reg_'+id_c+'"><a class="excluir_registro" href="#" title="Excluir este registro">Deletar</a>';
        html_new_reg += '<label>Campo_1</label> <input type="text" name="campo_1" placeholder="Insira novo registro" value="" autocomplete="off"/>';
        html_new_reg += '<label>Campo_2</label> <input type="text" name="campo_2" placeholder="Insira novo registro" value="" autocomplete="off"/></p>';

        $("#_INSERIR_").append(html_new_reg);
    });

    /* funcao para fechar */
    $("a.excluir_registro").click(function()
    {
        var del_id_c = $(this).parent().attr('id');
        console.log(del_id_c);

        //$("p#reg_"+del_id_c+"").remove();
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="_INSERIR_">  

    <p id="reg_1">
    <a class="excluir_registro" href="#" title="Excluir este registro">Deletar</a>
    <label>Campo_1</label> <input type="text" name="campo_1" placeholder="Insira novo registro" value="" autocomplete="off"/>
    <label>Campo_2</label> <input type="text" name="campo_2" placeholder="Insira novo registro" value="" autocomplete="off"/>
    </p>

    <p id="reg_2">
    <a class="excluir_registro" href="#" title="Excluir este registro">Deletar</a>
    <label>Campo_1</label> <input type="text" name="campo_1" placeholder="Insira novo registro" value="" autocomplete="off"/>
    <label>campo_2</label> <input type="text" name="campo_2" placeholder="Insira novo registro" value="" autocomplete="off"/>
    </p>
    
    <input type="submit" value="Inserir registro" class="botao_ficha" id="novo_reg"/>
</div>

  • Lauro’s answer is correct because event as click is only linked during loading, for dynamic elements it is necessary to use the on method().

1 answer

1

If the element was created dynamically use on of the element BODY instead of click and of course insert this id element containing the clickable class ex:

$(body).on('click', '.excluir_registro', function(){

     var id = $(this).attr('id');

     // ex de teste ou sua lógica
     alert(id);
});

Browser other questions tagged

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