-1

So I load this:

 $('#categories').load("/Category/GetCats");

from this controller

    public ActionResult GetCats()
    {
        var model = db.Cats
            .Where(c => c.user_id == 5);

        //var query = from c in db.Cats where c.user_id == 4 orderby c.catId select c;
        //var i = query.Count();
        //var results = query;

        return PartialView("_PartialGetCats", model);
    }

to render this view

  @foreach (var item in Model)
  {

    <tr>

        <td data-id="@item.catId">@item.item_name</td>

    </tr>

   }

The categories show but this function

     $('#categories tr').on("click", function () {
                var requestpage = "/Item/Partial?id=" + $(this).data("id");
                alert(requestpage);
                $.get(requestpage, function (result) {
                    $("#results").html(result);
                });

or any other jquery functions do not recognize the $('#categories tr). It will however recognize $('#categories'). I tested by removing the load() and hardocding this

   $('#categories').html('<tr data-id="5"><td>new data</td></tr>');

and it works. Whats going on?

EDIT: full Index.cshtml view

   @{
ViewBag.Title = "Home Page";
}



 <div id="categories">
 </div>

 <div id="results">
 </div>
 <div id="descrip">

 </div>
rogerthat
  • 1,805
  • 4
  • 20
  • 34

2 Answers2

1

You are using the on method a bit differently. Instead of the selector $('#categories tr'), you should use

$('#categories').on("click", "tr", function () { });

The reasons is, the on method gets hooked on whatever is in the selector and then captures the click event. Since, when you run this code, there is no tr in #categories, the on method never gets hooked. But if you use the method I stated, the on will get hooked on #categories and would work for every click on any tr in #categories

U.P
  • 7,357
  • 7
  • 39
  • 61
1

You either need to use event delegation or use the callback for jQuery .load().

jQuery .load() callback method:

Wait to wire up the click event until the HTML is in the DOM, this is why when you hardcode the HTML in via the .html() function it works, because the on("click" can find the elements to bind to. Instead do this:

$('#categories').load("/Category/GetCats", function () {
    $('#categories tr').on("click", function () {
        var requestpage = "/Item/Partial?id=" + $(this).data("id");
        alert(requestpage);
        $.get(requestpage, function (result) {
            $("#results").html(result);
        });
    });
});

Event delegation method:

This allows you to bind events to content that exists or may exist in the future, like this:

$('#categories').load("/Category/GetCats");

$("#categories").on("click", "tr", function(){
    var requestpage = "/Item/Partial?id=" + $(this).data("id");
    alert(requestpage);
    $.get(requestpage, function (result) {
        $("#results").html(result);
    });
});
Karl Anderson
  • 34,606
  • 12
  • 65
  • 80