Incerteza
Incerteza

Reputation: 34884

Dynamically add event handler to an href which is also dynamically generated

I have a button and when this button is clicked I need to generate a link dynamically and add a handler to it which shows a twitter bootstrap modal. I tried this:

$(function() {

  function showModal() {
    $("#myModal").modal("show");
  }

  $(document).on("click", "#my_btn", function() {
    //generating a link a adding a handler to it which is "showModal()"
    //.....
    $("#my_href").html("Some text123 <a href='#' onclick='showModal();'>test123</a>.");
    //.....
  })
});

But when I clink a this link the error is being thrown saying

Uncaught ReferenceError: showModal is not defined 

I can, of course, move showModal() out of $(function() {...}). But I was wondering, is there a better way to do it? And in general, is this a good way to achieve what I want?

UPDATE: Even after moving showModal() out of $(function() {...}) it doesn't work, it redirects me to the same page but doesn't show pop up.

Upvotes: 0

Views: 110

Answers (4)

Amarnath R Shenoy
Amarnath R Shenoy

Reputation: 5201

Here you should attach your event to the body or document not to the button

 $("body").on( "click","button[id$=my_btn]",  function(){

        alert( "hi" );
    })

Upvotes: 0

Ryan
Ryan

Reputation: 14649

$(function() {
   function showModal() {
     alert("Modal");
   }
    $('<a/>',{
        href: '#',
        text: "Click Me",
        click: function(e) {
          e.preventDefault();
          showModal();
        }
    }).appendTo('#my_href');
});

jsfiddle

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Use jQuery delegated event handlers to add the click handler

$(function () {

    function showModal() {
        $("#myModal").modal("show");
    }

    $(document).on("click", "#my_btn", function () {
        //generating a link a adding a handler to it which is "showModal()"
        //.....
        $("#my_href").html("Some text123 <a href='#' class='showmodal'>test123</a>.");
        //.....
    });

    $("#my_href").on('click', '.showmodal', showModal)
});

In your case you have a inlined event handler which is calling showModal, this expects a method named showModal in the global scope but you have added the method showModal as a closure method in the dom ready handler.

Upvotes: 1

user229044
user229044

Reputation: 239291

Don't use inline Javascript. You've posted a perfect example of how you should be doing this right in your question: Use .on on the containing element.

 $(document).on("click", "#my_btn", function() {
    $("#my_href").html("Some text123 <a href='#'>test123</a>.");
 });

 $('#my_href').on('click', 'a', showModal);

Upvotes: 2

Related Questions