0

i append input in div:

$("#menuItems").append("<input type='button' id='"+$("#category").val()+"' class='menuItemDelete' value="+$("#category :selected").text()+" ><br>");

then i want to access element by class name but it does not give any responce. i try this:

$(".menuItemDelete").click(function(){

    alert("abc");

});

and also try this:

$(".menuItemDelete").on("click", function(){

    alert("abc");

});

how can i access it ?

Muhammad Rohail
  • 215
  • 3
  • 13

3 Answers3

1

Try this :

$("#menuItems").on("click",'.menuItemDelete', function(){
   alert("abc");
});

Consider to read this Event Delegation Concept for dynamic element created like yours.

Norlihazmey Ghazali
  • 8,762
  • 1
  • 19
  • 37
0

Use appendTo to get a reference back to the added elements

var els =$("<input type='button' id='"+$("#category").val()+"' class='menuItemDelete' value="+$("#category :selected").text()+" ><br>").appendTo("#menuItems");

els.filter('.menuItemDelete').click(...)

But since you are dealing with dynamic elements, you can also use event delegation. The below handler can be added on dom ready and then there is no need to worry about when the dynamic elements are added

//on dom ready handler
$('#menuItems').on('click', '.menuItemDelete', function(){

});

//later somewhere else
$("#menuItems").append("<input type='button' id='"+$("#category").val()+"' class='menuItemDelete' value="+$("#category :selected").text()+" ><br>");
Arun P Johny
  • 365,836
  • 60
  • 503
  • 504
0
$(document).on("click", ".menuItemDelete", function(){
    alert("abc");
});
Peter
  • 447
  • 2
  • 10