-1

I have the following which works fine:

      $('<li><a id=' + loc.locId + ' href="/DataEntry"  rel="external">' + loc.locName + '</a></li>').appendTo("#btnList");

       $("#btnList a").click(function () {
            alert(siteName);
            localStorage["dataEId"] = $(this).attr("id");
            localStorage["dataESiteName"] = siteName;
            localStorage["dataESysName"] = sysName;
            localStorage["dataELocName"] = $(this).text();

         }

When I have the following, I can't even get to the click to display an alert message:

$.getJSON('/Home/GetLocType', { "locId": loc.locId }, function (result) {
    var str = JSON.stringify(result);

    if (str == '1') {
        $('<li><a id=' + loc.locId + ' href="/DataEntry"  rel="external">' + loc.locName + '</a></li>').appendTo("#btnList");
    } else {
        $('<li><a id=' + loc.locId + ' href="/DataEntry/PotableForm"  rel="external">' + loc.locName + '</a></li>').appendTo("#btnList");
    }
    $("#btnList").listview('refresh');
});

$("#btnList a").click(function () {
    alert(siteName);
    localStorage["dataEId"] = $(this).attr("id");
    localStorage["dataESiteName"] = siteName;
    localStorage["dataESysName"] = sysName;
    localStorage["dataELocName"] = $(this).text();
}

Note sure what the difference is. I need to use Json as based on value, I need to go to a either of the 2 hyperlinks.

0

1 Answer 1

2

Use event delegation since anchor is created dynamically in your ajax call or bind the event (only for the added element) inside the ajax success callback. on syntax will work if your jquery version >= 1.7 for earlier versions take a look at live

  $("#btnList").on('click', 'a', function () {
        alert(siteName);
        localStorage["dataEId"] = $(this).attr("id");
        localStorage["dataESiteName"] = siteName;
        localStorage["dataESysName"] = sysName;
        localStorage["dataELocName"] = $(this).text();

    }  

Your first syntax works because it binds the click event to the anchor that exists underneath btnList, but it doesn't bind event to the ones added during the ajax calls in a later point in time.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.