+ 1

How do I create a function for all elements in a table without coding "onclick" for each and every one?

I have a calendar and for each date I want to be able to click it and run the same function. How do I code that? For example, using query selector, what designation would cover any day of the week?

11th May 2019, 11:54 AM
Stan Berger
Stan Berger - avatar
10 ответов
+ 6
You can add an listener on table and detect which child is clicked from there... A sample here https://code.sololearn.com/WXSe7O1kzf39/?ref=app
11th May 2019, 1:02 PM
KrOW
KrOW - avatar
+ 3
Stan Berger You are welcome 😉 👍
12th May 2019, 5:52 AM
KrOW
KrOW - avatar
+ 2
KrOW, this is great! Just what I needed because I do need to know which day has been selected!! Thanks!!
11th May 2019, 9:11 PM
Stan Berger
Stan Berger - avatar
+ 1
If I wanted to create a lot of buttons, I'd probably create them from the JS code, using a loop, giving indexes to each button.
11th May 2019, 12:39 PM
HonFu
HonFu - avatar
+ 1
Wouldn't it also be possible to add a listener to the table so that when the click event from the day-element bubbles up to the containing table the same function is run but with the clicked element as event.target?
11th May 2019, 12:48 PM
Michael U.
Michael U. - avatar
0
Or just like i did in this code, in init function. Little bit system breaking, but works. Or use: $("td").each( cell => cell.click( e => { alert(e.target); } ) ); https://code.sololearn.com/WgUeybi1pq3T/?ref=app
11th May 2019, 1:24 PM
Maneren
Maneren - avatar
0
KrOW, just when you manage to click between the cells, it shows whole table content. Maybe it would be better to add click listener to cells or add if statement.
12th May 2019, 7:46 AM
Maneren
Maneren - avatar
0
Good point! But, since I can't give same id to each cell, how do I use ClassName array for example to achieve this. Or what "if" statement do you mean?
12th May 2019, 12:30 PM
Stan Berger
Stan Berger - avatar
0
Infact mine was a sample... Inside the handler you have to handle the case for handle all childs (eg. identify them) and, if necessary, when no child is clicked (eg. click on the table).... I have update my sample code for this
12th May 2019, 4:02 PM
KrOW
KrOW - avatar
0
Thanks again! I am a novice tinkerer and I am amazed at this community - I have learned so much!! I am now hooked on coding :)!!
12th May 2019, 4:09 PM
Stan Berger
Stan Berger - avatar