data from onchange event
Hey quick question, i feel like an idiot.
I'm used to angular as a framework, and handlebars obviously is much more toned down compared to it, so I can't seem to figure out the correct way to do this:
I have a couple checkboxes representing a numeric value, so if i check the third checkbox, the value is set to three. If I check the second checkbox, the value is set to two, ecc.
How do I apply a value to the individual checkboxes that is included in the event object passed to the onchange event?
I imagine it'd look like something along these lines:
we click checkbox 2
and inside the .js we got something like:
Is this actually doable like i think it is, or am I too spoiled by other frameworks?
Any answer is appreciated:chefkiss:
7 Replies
So the
event
argument in your listener is a JavaScript Event, so you probably want event.currentTarget.checked
(for things like text inputs you'd do event.currentTarget.value
instead)Well yes, but I also need a numeric value connected to the checkbox, not just its checked status and that is what i am struggling with
(
event.currentTarget
is the HTML Element that you put the event listener on)
Oh! Okay
So instead of data=1
, use data-data=1
then you access it using event.currentTarget.dataset.data
(example that doesn't use "data" as a keyword: data-some-name-you-want=2
and in the JS event.currentTarget.dataset.someNameYouWant
)You are a saint, that is exactly what I'm looking for. I'll be trying that tomorrow, thanks a lot. Could you maybe give a term or something that I can use to further google info on this data object?
For sure! That's what is called an "data attribute"
MDN has a pretty great page about it here: https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
MDN Web Docs
Using data attributes - Learn web development | MDN
HTML is designed with extensibility in mind for data that should be associated with a particular element but need not have any defined meaning. data-* attributes allow us to store extra information on standard, semantic HTML elements without other hacks such as non-standard attributes, or extra properties on DOM.
Amazing, I've been stumbling in the dark for a couple hours feeling like a dumbass cause this kinda shit seems so basic coming from other spaces of webdev.
Thanks again❤️
You're welcome! And yeah, some of the native HTML stuff that needs to be done for Foundry gets hidden by JS frameworks, so it can be rough sometimes.
Though a nice thing is that almost everything involved with Foundry dev can apply when using JS frameworks to some extent