Reputation: 171
I'm new to web design and have a problem I don't really know how to solve in the most eloquent way. I have 7 weekday elements, each 2 dropdowns. A dropdown has 24 options, 1 for each hour of the day. That means 336 possible options a user can click on in total.
I need to assign a function to each of those 336 elements that will update the text in the corresponding box the dropdown menu came from.
I know how to do what I'm trying to achieve, but I'm not sure how to do it 'properly'. I could write my function that updates the text based on what you clicked on. Then I could go through and manually assign a unique ID to each of my 336 elements, then write a function that loops through and assigns my first function to all of them. Although this would mean manually assigning 336 unique ID's in my HTML. Something feels wrong about this? is there any better way?
I feel like I'm missing something very obvious that would make this much easier - maybe I'm taking a completely wrong approach?
Upvotes: 3
Views: 203
Reputation: 3898
Assign a single onclick
event handler to all 336 of your elements. Attached to the Event parameter that is passed to the event handler is a property target
, which is the element on which the event was fired.
Then find the parent of this element (simply node.parentElement
), and do your processing on it.
P.S. you don't need to have a unique id on an element in order to assign it an event handler.
Try:
document.querySelectorAll('.el').forEach(function(t) {
t.onclick = func;
});
Upvotes: 1
Reputation: 1557
You should not use IDs and use just a single event for all elements.
There's a concept called event delegation, where you attach an event to a parent node, and it will handle that event for all child nodes. Since events "bubble up" in javascript, any event will eventually hit the parent node and trigger it. When that happens, you can check the original target of the event, and check if it's one of the classes you care about.
Here's an example: https://davidwalsh.name/event-delegate
Many libraries offer their own support for this, but it's actually pretty easy to do.
Upvotes: 3
Reputation: 871
Try using "this
" keyword than assigning ids manually.
So instead of document.getElementById(id)
you can use this
for example, instead of
HTML
<element id="myid" onClick="changer(myid);"> </element>
JS
function changer(id)
{
document.getElementById(id).innerHTML="changed";
}
You may try
HTML
<element onClick="changer(this);"> </element>
JS
function changer(obj)
{
obj.innerHTML="changed";
}
Upvotes: 0
Reputation: 2396
There are other functions you can use to traverse the DOM. Check out the Element documentation.
There are countless ways to achieve what you want here, but I would do this by assigning a shared class like day
to all your day options, and another class like start-time
and end-time
for the time options. Then I'd bind the function to all elements returned by document.getElementsByClassName('day')
Upvotes: -1