This is the code –
<div class="filter-box" id="categoryFilter">
<input type="checkbox" id="3" name="Education" value="3">
<label for="Education">Education</label>
<input type="checkbox" id="12" name="Employment" value="12">
<label for="Employment">Employment</label>
<input type="checkbox" id="5" name="Goods and Services" value="5">
<label for="Goods and Services">Goods and Services</label>
</div>
I need to target the value or the ID of the checkbox clicked so I can add it to the URL string of an API call.
How can I target the checkbox so that I can write an on click event that returns the value?
4
Answers
You can add an event listener on the containing
<div>
element for the change event. Then, you can get thevalue
from the event’s target.Using jQuery:
I solved it with this solution, you have to use forEach and each loop functions then applying onchange event on them to get their value and ID
for
should match theid
, not the Input’sname
id
andfor
attribute and wrap your inputs into the<label>
.prop()
to get the desired property valueWith the death of IE browsers, and evergreen browsers keeping pace with the newest ECMAScript goodies, jQuery is not necessary nowadays. A pure JavaScript approach, without the overhead of a library like jQuery would be:
Notice also, the above example in pure JavaScript uses Event delegation, similar to what you would do in jQuery with
$(parent).on("eventName", "dynamicChild", fn)
– which will work even for dynamically created checkbox elements.