Tuesday, December 22, 2015

Jquery dynamically generated element (class, ID) click not working




For example
  <script type="text/javascript">

        $(document).ready(function() {

            $(".div.ajax_list").click(function() {
                $(".test").html("<button class='sendmail'>click me</button>")
            });   

            $(".sendmail").on('click',  function(){
                alert('mail is sent');
            });
        });

    </script>
You will find sendmail button did not work.
change
            $(".sendmail").on('click',  function(){
                alert('mail is sent');
            });
to
            $(".sendmail").live('click',  function(){
                alert('mail is sent');
            }); 
will fix the problem.

or
             $(document).on('click',  '.sendmail00', function(){
                alert('mail is sent');
            });

Reference:
http://stackoverflow.com/questions/6658752/click-event-doesnt-work-on-dynamically-generated-elements

No comments:

Post a Comment