CinnamonBun
CinnamonBun

Reputation: 1150

Calling a click event of a dynamically created element

I'm pretty new to all things javascript related, and I seem to have got myself in a pickle. I'm creating a site which displays a seating plan of an office. When the page loads, I load data retrieved from the database, into a function that loops through it and creates an anchor for each person.

This is my method:

       function getDesks(coordsArr) {
            for (var i = 0; i < coordsArr.length; i++) {
                var element = $("<a href='' class='deskBtn' data-name='" + coordsArr[i].UserName + "'>.</a>");
                $(element).css({
                    "top": coordsArr[i].DeskYCoord,
                    "left": coordsArr[i].DeskXCoord
                }).appendTo(".map");
            } 
        }

The problem i'm having is where to place the following ajax click event.

  $('.deskBtn').on('click', function () {
                var user = $(this).attr("data-name");
                console.log(user);

                $.ajax({
                    url: "/Home/GetUserData",
                    type: "GET",
                    data: {user: user},
                    success: function (data) {

                    }
                });
            });

I tried placing it after the for loop, but when I click one of the anchor tags the data gets logged to the screen, however, it quickly vanishes. Any suggestions would be great.

Upvotes: 0

Views: 60

Answers (3)

pCyril
pCyril

Reputation: 134

You should try with a live

$(document).ready(function(){
    $('.deskBtn').live('click', function(){

    });
});

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

Delegate the event to a static element. Do it for body:

$('body').on('click', '.deskBtn', function () {

    var user = $(this).attr("data-name");
    console.log(user);

    $.ajax({
        url: "/Home/GetUserData",
        type: "GET",
        data: {user: user},
        success: function (data) {

        }
    });
});

Upvotes: 0

JaredPar
JaredPar

Reputation: 754725

Why can't you just add the handler inside the for loop?

$(element).on('click', function() { ... })

Upvotes: 1

Related Questions