GrantU
GrantU

Reputation: 6555

jquery Pass ID of generated link being clicked

How do I passed the id the item that has been clicked from the generated code below?

In a js file:

$('#smartpage_table tbody').append('<tr class="child"><td>' +  val.fields.link +
              '</td>' +
              '<td> <a href="" id="' + val.fields.id + '" >'
              + val.fields.link + '</a> </td>' +
              '</tr>');


        });

On Page I have the following

**$("#test").click(function() {
    alert(ID WAS PASSED);
});**

When one of the generated links are clicked I want the ID of the link to be passed to the above code and output in the alert box. How can this be done?

Upvotes: 0

Views: 78

Answers (3)

Jeroen1984
Jeroen1984

Reputation: 1686

You can, for example, add a class to the a elements, and then use a class selector for your click event:

$('#smartpage_table tbody').append('<tr class="child"><td>' +  val.fields.link +
              '</td>' +
              '<td> <a href="" class="myClass" id="' + val.fields.id + '" >'
              + val.fields.link + '</a> </td>' +
              '</tr>');


        });

Then this will work:

$(".myClass").click(function() {
    alert($(this).attr('id'));
});

Upvotes: 0

palaѕн
palaѕн

Reputation: 73896

Try this:

$("#smartpage_table").on("click", "a", function () {
    alert(this.id);
});

Upvotes: 1

thatidiotguy
thatidiotguy

Reputation: 8981

$("#test").click(function() {
    alert('test must have been passed because IDs are unique on HTML pages.');
    alert('but maybe I meant class so ' + $(this).attr('class') + ' was passed.');
});

Upvotes: 1

Related Questions