sarovarc
sarovarc

Reputation: 407

Bind jQuery to Multiple Elements

I am populating a table with some data. I do not know how many rows the table contains. Each row has a link which if I click shows me the details of the said row.

Now I wish to bind a single jQuery to each of these hyperlinks. This function will receive the unique id of each row; and do an ajax to fetch more data for the row:

Here is what the HTML looks like (with id being an actual number):

<a id="view-id">
    <img src="/resources/assets/graphics/view.png" class="action-button" alt="View" title="View" />
</a>

My jQuery function will look like so (with id being an actual number):

$(document).on('click', '#view-id', function() {
    //Do Something
});

Since I do not know how many row's I will have; how can I bind my jQuery function to each of these hyperlink elements.

I read somewhere that I can do the following:

$(document).on('click', '#view-1,#view-2,#view-3', function() {

But this doesn't seem very efficient. Any ideas which direction I should head in. Bear in mind the table content is loaded via an AJAX call : )

Thanks.

Upvotes: 1

Views: 958

Answers (4)

Benjamin Ray
Benjamin Ray

Reputation: 1870

Assign a class to the elements to be bound, and use the class name in the selector to select all of the elements with that class. The $(this) will reference the object clicked, at which point you can do $(this).id to get the clicked object's ID.

HTML:

<a id="view-id1" class="class-name">
    <img src="/resources/assets/graphics/view.png" class="action-button" alt="View" title="View" />
</a>
<a id="view-id2" class="class-name">
    <img src="/resources/assets/graphics/view.png" class="action-button" alt="View" title="View" />
</a>

JavaScript:

$(document).on('click', '.class-name', function() {
    // 'this' references the item clicked.
    alert(this.id + ' is the ID clicked.');
});

Upvotes: 3

Shailesh Katarmal
Shailesh Katarmal

Reputation: 2785

$('#abc, #xyz, #pqr').bind('click', function () {
      alert("hello");
});

Use comma with multiple elements with id, OR elements to bind event.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388416

Add a class to all the elements and then use that class to target the anchor element

<a id="view-id" class="view-id">
    <img src="/resources/assets/graphics/view.png" class="action-button" alt="View" title="View" />
</a>

then

$(document).on('click', '.view-id', function() {
    //Do Something
});

Upvotes: 4

Paulo Henrique Martins
Paulo Henrique Martins

Reputation: 1490

Why don't you add a class to each of those elements and bind them using the class selector?

<a id="view-id" class="view-item">
<img src="/resources/assets/graphics/view.png" class="action-button" alt="View" title="View" /></a>

$(document).on('click', '.view-item', function() {
    //Do Something
});

Upvotes: 1

Related Questions