-1

I am creating a button on the fly and appending it to a div. I want to capture the click event on that button.

function(){
  $('#menuDiv').append('<div class ="buttonWrapper"><input type="button" id="addToOrder" name="addToOrder" value="Add to order"></div>');
}

and then trying to capture the click event with this

$("#addToOrder").click(function () {
  //Grab the selections made on the form
  window.alert('i m in add to order');
  updateOrderWindow();
});

This function is not executing. Don't know why. I have also tried it with the .buttonWrapper div class but it didn't work.

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Novice
  • 515
  • 7
  • 22

3 Answers3

3

You may want to use the on handler to bind dynamically created elements:

$('#menuDiv').on('click', '#addToOrder', function () {
    //Grab the selections made on the form
    window.alert('i m in add to order');
    updateOrderWindow();
});

This will bind the event itself to the menuDiv element, and will run the click handler for any children #addToOrder

James Hay
  • 7,115
  • 6
  • 33
  • 57
0

Problem that your button created dynamically

You can try to use next code

$(document).on("click", "#addToOrder", function(){
  alert ('button clicked');
});
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Fullbalanced
  • 87
  • 11
0

Try with this

$(function(){
  $('#menuDiv').append('<div class ="buttonWrapper"><input type="button" id="addToOrder" name="addToOrder" value="Add to order"></div>');
});
$('#menuDiv').on('click','#addToOrder', function (){
  //Grab the selections made on the form
  window.alert('i m in add to order');
  //updateOrderWindow();
});
<div id="menuDiv"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Jishnu V S
  • 8,164
  • 7
  • 27
  • 57