Get id of dynamic added element in onclick

Viewed 1549

There is a function that is created a html elements on page when document is ready. I have to create onclick() event on that elements and use there an element id.

My code is:

$('document').ready(function(){
    addNewElementToContainer();
});

function addNewElementToContainer(){
 $("#myContainer").append('<div onclick="myClickEvent(this.id)" value="1" >Click me</div>');
}

function myClickEvent(id){
    alert("ID: " + id);
}

The id is set correctly (check it on page inspector) but the result is wrong - "ID: ". So it looks like the id is empty.

How is it possible to solve that problem?

@UPDATE Html file is:

<html lang="en">
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>

    <body>
        <div id="myContainer"><div>
    </body>

    <script>
        $('document').ready(function(){
            addNewElementToContainer();
        });
        function addNewElementToContainer(){
            $("#myContainer").append('<div onclick="myClickEvent(this.id)" value="1" >Click me</div>');
        }
        function myClickEvent(id){
            alert("ID: " + id);
        }
    </script>
</html>
3 Answers

Just give the id and value for your Html element as below:

$('document').ready(function(){
            addNewElementToContainer();
        });
        function addNewElementToContainer(){
            $("#myContainer").append('<div onclick="myClickEvent(this.id, this)" id="id1" data-value="1" >Click me</div>');
        }

function myClickEvent(id, obj){
            alert("ID: " + id);
            val = obj.getAttribute('data-value');
            alert(val);
        }
<html lang="en">
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    </head>

    <body>
        <div id="myContainer"><div>
    </body>
    </script>
</html>

it works! Is there any way to get the element value as well?

yes, eg with jquery

$(this).attr('value');

The context "this" has no property id set.

Related