0

I am building a Modal dynamically. I want to make some buttons in this modal to open a SubModal. The buttons show up in html, but clicking these buttons does nothing. Here is my code.

const subtaskList = document.getElementById('subtaskList');
for (const subtaskIndex in task.subtasks) {
    const subtaskButton = document.createElement('button');
    subtaskButton.classList.add('taskModalSubtaskButton');
    subtaskButton.onclick = () => {
        openSubTaskModal(task.subtasks[subtaskIndex], task);
    }
    subtaskButton.innerText = task.subtasks[subtaskIndex].name;
    subtaskList.appendChild(subtaskButton);
    subtaskList.innerHTML += '<br>';
}

While troubleshooting I made an array to hold the buttons and used console.log() to see its elements. They all had the onclick function. I've clicked the buttons from the dev console by getting their class name and nothing, so I know it's not a display issue. I feel like I am misunderstanding something and any help would be appreciated.

0

1 Answer 1

1

The problem is subtaskList.innerHTML += '<br>'; it is good idea to use subtaskList.appendChild(document.createElement("br")); instead.

Here is working snippet:

function doSomething(url) {
    alert(url);
}

const subtaskList = document.getElementById('subtaskList');
for (var i = 0; i < 3; i++) {
    const subtaskButton = document.createElement('button');
    subtaskButton.classList.add('taskModalSubtaskButton');

    subtaskButton.innerText = "name" + i;

    subtaskButton.onclick = (function (url) {
                return function () {
                    doSomething(url);
                };
            })("URL #" + i)

    subtaskList.appendChild(subtaskButton);
    subtaskList.appendChild(document.createElement("br"));
}
<div id="subtaskList"></div>

Also I change a bit onclick function to send correspond index to doSomething function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.