I am working on building an app, and I have about twelve checkboxes
with svgs
that appear next to the checkbox when that particular checkbox is checked by the user. Example checkbox below:
<input type="checkbox" id="stdyCoord" name="resPos1" value="2" class="optnsArea2">
<label for="stdyCoord">
<object data='images/icons/White_SVG/checkmark2-svg.svg'
class='img-responsive titleSVG'
type="image/svg+xml"
style='display: none' id='svgStdyCoord'>
</object>
Study Coordinator
</label>
I have this working pretty seamlessly with the below JS function:
$('#stdyCoord').click(function (event) {
$('#svgStdyCoord').toggle();
});
Is there a way to avoid having to write out 12 functions that are the same for each different checkbox? I tried to use if/else statements but couldn’t get it to work.
2
Answers
A couple of things.
I moved the checkbox inside the label. That way you don’t need an id for the checkbox or a "for" for the label.
I gave the checkbox a class of hasSVG so that we know which ones to give the click handler.
The click function itself just gets the next element after the one that was clicked. So for the hasSVG checkboxes, that’s the object you want to toggle.
Write your own native JavaScript Web Component
<marked-checkbox>
,Supported in all modern browsers.
drawback of jQuery is code can only operate on existing DOM nodes.
Web Components automagically upgrade, you can
define
a Web Component any time you want.