Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Uncaught TypeError: cancel is not a function

I’m new to JavaScript and even though I defined a function called cancel, I get the uncaught type error. Couldn’t understand why. The function was defined before it was called.

function cancel(memberID){
    document.getElementById(`remove_${memberID}`).style.display = "block";
    document.getElementById(`edit_${memberID}`).style.display = "none";
}

document.addEventListener("DOMContentLoaded", function(){

    const button = document.querySelectorAll("#edit_profile")
    button.forEach(function(button){
        button.onclick = function(){
            
            const memberID = button.dataset.id;
            const username = document.getElementById(`username_${memberID}`);
            const skills = document.getElementById(`skills_${memberID}`);
            const bio = document.getElementById(`bio_${memberID}`);

            let edit_username = document.createElement("input");
            edit_username.setAttribute("type", "text");
            edit_username.setAttribute("value", username.innerHTML);
            edit_username.id = "edit_username";
            edit_username.className = `form-control username ${usernameID}`;

        
            let cancel = document.createElement("button");
            cancel.innerHTML = "Cancel";
            cancel.className = "btn btn-danger col-3";
            cancel.id = "cancel";
            cancel.style.margin = "10px";

            document.getElementById(`edit_${memberID}`).append(edit_username);
            document.getElementById(`edit_${memberID}`).append(cancel);
        
            document.querySelector("#cancel").onclick = function(){
                cancel(memberID)
            }
        }
    })
})

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You’re hiding the cancel function by creating a local variable with the same name. Give it a different name (e.g., cancelButton) and you should be OK:

let cancelButton = document.createElement("button");
cancelButton.innerHTML = "Cancel";
cancelButton.className = "btn btn-danger col-3";
cancelButton.id = "cancel";
cancelButton.style.margin = "10px";
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading