+ 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?
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
+ 3
Stan Berger You are welcome 😉 👍
+ 2
KrOW, this is great! Just what I needed because I do need to know which day has been selected!! Thanks!!
+ 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.
+ 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?
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
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.
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?
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
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 :)!!