0
votes

I'm trying to use jquery to add a .click() function to several dynamically generated spans using their class. What I'm trying is essentially:

$(".spanClass").click(function () {});

I have also tried:

$(".spanClass").on("click", function () {});

Now, this all works, to an extent. My issue is that the .click() only gets assigned to the first span with this class. Every other span with this class does absolutely nothing when I click it. Obviously, I need every span with the class to have the .click().

It may be important to note that my spans are contained inside cells of a table. Each span is in a different cell, and there is only one cell per table row that contains a span.

Any help is greatly appreciated.

JSFiddle of what I'm working with. JSFiddle link

Edit note: Originally this question involved using an ID instead of a class. People noted I should use class instead, and should edit the question if that didn't work.

Edit 2: Added info about tables.

Final edit: Best solution chosen. If you come across this issue, best answer is functioning. My issue was a scripting issue inside my .on("click") function itself.

1
IDs should be unique on each page - John Conde
Fair enough, but even doing it with a class, it still has the same behavior. - user3712957
You should probably edit the question/title to avoid getting downvoted into oblivion. If you want to hit every span with a certain class, $('.classname').click... should work. - djbhindi
The code you are providing is correct. There must be some other problem, maybe a not valid HTML structure or a problem when dynamically generating the spans. - Teetrinker

1 Answers

3
votes

You need to use a class instead of an id.

The id should be unique in the entire page:

The ID must be unique in a document, and is often used to retrieve the element using getElementById.

Because of this, trying to assign the click event to it will fire only on the first occurence of the span with id = spanId

See example below, and use .on("click", function()) instead of .click()

$(".yourspanclass").on("click", function(){
    // do what you need on click 
});

see a working example HERE