Sahil Paudel
Sahil Paudel

Reputation: 321

Uncaught ReferenceError: function is not defined but it is defined

for(let i = 0; i < row.length; i++){
        let ref_num = row[i].getElementsByTagName('th')[0].innerText;
        row[i].getElementsByTagName('th')[0].innerHTML = "<button onclick=generateProcessLogQuery(this.value)>"+ref_num+"</button>"
        console.log("Ref Number : ",ref_num);
}

function generateProcessLogQuery(refresh){
        console.log("Hrere : ",refresh)
}

I am getting:

Uncaught ReferenceError: generateProcessLogQuery is not defined

but you can see that it is defined.

Upvotes: 0

Views: 8693

Answers (2)

Ben in CA
Ben in CA

Reputation: 851

I ran into something similar; in my case I had the function defined inside a document ready.

$(document).ready(function() {
// function was here and should not have been to call from HTML
});

Upvotes: 1

Quentin
Quentin

Reputation: 944451

While it is defined in the fragment of code you have shown us, it isn't defined in the scope that the onclick function eventually runs in.

Don't generate JS nested in HTML by mashing strings together.

Use DOM. This lets you keep references and scope.

let button = document.createElement("button");
button.addEventListener("click", function (event) {
    generateProcessLogQuery(this.value);
});
button.appendChild(document.createTextNode(ref_num);
row[i].getElementsByTagName('th')[0].appendChild(button);

NB: It is odd to use this.value on a button you are defining without a value attribute.

Upvotes: 4

Related Questions