I use jquery and es6 template strings to create a checkbox with a label:
function createCheckBx(id, text) {
return $(`<div>
<input id ="${id}" type="checkbox"/>
<label for="${id}">${text}</label>
</div>`);
}
Now I would like to attach an eventlistener to the checkbox
checkBox = createCheckBx("42", "Answer");
cb.???.addEventListener("change", (evt) => {
// do smth. when toggled
})
but the div is not attached to the dom yet so I can't use document.getElementById (or jquery's $("#...") and I don't want to access it by any kind of index like cb.childNodes[0], since the caller can't know the index and the html structure may change. Any help?
kindly regards, AJ
Just because the element doesn't yet exist in the DOM doesn't mean you can't attach an event handler to it. The only issue in your example is the syntax you're using as you're mixing jQuery and plain JS methods. You should stick to one or the other.
As you're including jQuery in the page, here's how to make your example work:
let createCheckBox = text => $(`<div><label><input type="checkbox" />${text}</label></div>`);
let $checkBox = createCheckBox("Answer");
$checkBox.on('change', e => {
console.log(`Checkbox checked? ${e.target.checked}`);
});
// add the checkbox to the DOM at some point:
$('body').append($checkBox);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
Note that I removed the id attribute from the function which creates the element and also the HTML it generates. This is because creating id at runtime is an anti-pattern and should be avoided. Use common classes instead.
Also note that you may be better served by creating a single delegated event handler to handle all your dynamically appended content, instead of attaching an event as you create the new elements. Here's an example of how to do this:
let createCheckBox = text => $(`<div><label><input type="checkbox" />${text}</label></div>`);
let $container = $('.checkbox-container');
$('button').on('click', e => $container.append(createCheckBox("Answer")));
$container.on('change', ':checkbox', e => {
console.log(`Checkbox checked? ${e.target.checked}`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button type="button">Add</button>
<div class="checkbox-container"></div>