Rash J
Rash J

Reputation: 143

JS - Get value on click event from dyamically added elements

I would like to get value on click event from dynamically added elements but something goes wrong.

My code is:

<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
        $("button").click(function(){
            $("#myContainer").append("<div class='remove' value='myValue'>click to display value</div>"); 
        });
        $(document).on("click", ".remove" , function() {     
            alert($(this).val());  
        });
    });
</script>
</head>
<body>
    <button>Add new list item</button>
    <div id="myContainer">
    </div>
</body> 
</html>       

When I am clicking on the created dynamically div there is empty alert insted of myValue.

What should I change?

Upvotes: 0

Views: 52

Answers (2)

sauhardnc
sauhardnc

Reputation: 1961

this should work for you. ↓↓

$(document).ready(function(){
  $("button").click(function(){
    $("#myContainer").append("<div class='remove' value='myValue'>click to display value</div>"); 
  });

  $(document).on("click", ".remove" , function() {     
    alert($(this).attr('value'));  
  });
});
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>
  <button>Add new list item</button>
  <div id="myContainer"> </div>
</body> 
</html>

Upvotes: 1

Jonson
Jonson

Reputation: 336

Try

$(document).on("click", ".remove" , function() {
    alert($(this).attr('value'));
});

Instead of

$(document).on("click", ".remove" , function() {     
    alert($(this).val());  
});

Upvotes: 3

Related Questions