I have a partial inside a partial which has radio button
s or check box
es. What I want to do is to get the radio button or checkboxes which are clicked. Now initially when the page is loaded I am able to get the buttons but when I go to the next partial I am not able to get the new buttons. How can I get the buttons of the new partial everytime some button is clicked in a separate js. If I use onclick
function inline with radio button
or checkbox
then the function is called correctly but I want to get the present displayed elements in a separate js file.
I tried to use window.addEventListener('change')
. If I use this then the function is not called on first click but in the subsequent clicks it calls that many number of times i.e., on second click the function is called once, on third click the function is called twice and so on.
// window.addEventListener('change', () => {
window.addEventListener('DOMContentLoaded', () => {
if (document.querySelectorAll('[name="question[answer_id]"]').length !== 0) {
document.querySelectorAll('[name="question[answer_id]"]').forEach((questionAnswerButton) => {
questionAnswerButton.addEventListener('click', (event) => {
console.log(event);
fetchCall(event.target.value);
});
});
}
});
radio_button_partial.html.erb
<%= radio_button_tag 'question[answer_id]',
answer.id,
(user_answer == answer.id),
{
class: 'answer_opt',
// onclick: fetchCall("<%= answer.id %>")
} %>
Here if I uncomment the onclick function then I get the desired functionality. But what should I change in this that I get the present displayed radio buttons from the separate js file?