mrjayviper
mrjayviper

Reputation: 159

click event not triggered on my link, how to fix?

I am creating several links (using jQuery html function) on the FLY based on the JSON data I am receiving. Each of the link have the id "idxxxx" (xxxx is the primary key).

This is the javascript code I'm using:

$(document).ready(function(){
    onLoad();

    $("a[id^=id]").on("click", function(event) {
        alert('here');
    });

    function onLoad() {
        $(document).prop("title", "Course Listing");

        getCourses();
    }

    function getCourses(name) {
        $.ajax({
            url: "http://localhost/courses/getCourses?format=json"
            , dataType: "json"
            , data: {name: name}
            , success: function(data, status) {
                populateCourses(data);
            }
        });
    }

    function populateCourses(data) {
        var html = "";

        if (data.length > 0) {
            $.each(data, function () {
                html += "<a href='##' id='id" + this.ID + "'>Edit</a><br />";
            });
        }

        $("#courselist").html(html);
    }
});

My problem is that the links created does not trigger on the click event.

As a test, I manually created a link tag on my page with the similar id as the other links and I am not encountering the same problem. The alert box displays fine.

Any ideas on how to fix this? Thanks

Upvotes: 0

Views: 61

Answers (2)

TheVillageIdiot
TheVillageIdiot

Reputation: 40497

try this:

$(function() {
  var ar = [];
  for (var i = 1; i <= 10; i++) {
    ar.push("<a href='#' id='id" + i + "'>Link " + i + " </a>");
  }

  $("#courselist").html(ar.join(''));

  //THIS WILL ADD CLICK HANDLER TO ANY A INSIDE div#courselist
  //EVEN IF IT IS ADDED AT RUNTIME
  $("#courselist").on("click", "a[id^='id']", function(event) {
    $("#log").append($("<span/>").text($(this).text()));
  });
});
a {
  margin: 2px;
  padding: 3px;
  outline: none;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
     </script>
<div id="courselist"></div>
<div id="log"></div>

Upvotes: 2

Wayne Ellery
Wayne Ellery

Reputation: 7958

The issue is you are adding the onClick before the links have been added because the links are add some time after the ajax returns which is asynchronous. The simplest solution is to add the click in the populateCourses method:

function populateCourses(data) {
    var html = "";

    if (data.length > 0) {
        $.each(data, function () {
            html += "<a href='##' id='id" + this.ID + "'>Edit</a><br />";
        });
    }

    $("#courselist").html(html);

    $("a[id^=id]").on("click", function(event) {
        alert('here');
    });
}

http://jsfiddle.net/z6bnwjy7/

Upvotes: 1

Related Questions