mdev mdev - 7 months ago 78
Javascript Question

Button creates "Uncaught SyntaxError: Unexpected token (" in "<DOCTYPE html>"

When the button created below is pressed, it returns the following error:

"1 Uncaught SyntaxError: Unexpected token ("

in DOCTYPE html at the top of the html file.

function createButton(check){
var btn = document.createElement("button");
btn.setAttribute("onclick", "function(){checkQuestion(check);}");
var textbtn = document.createTextNode("Submit");

check is a variable that refers to a number that specifies a question, which is checked with checkQuestion().

Is the error from the code above?


onXYZ attribute-style handlers are meant to be step-by-step code; the browser wraps them in a function. So that onXYZ handler ends up being something like this:

function onclick(event) {
    function() {

You can see the problem: The content of the generated function is invalid.

So if using an onXYZ handler, it should be:

btn.setAttribute("onclick", "return checkQuestion(check);"); 

...but note that check must be a global variable in that case.

Instead, you may want to assign to the onclick property instead:

btn.onclick = function() { return checkQuestion(check); };

...which allows it to work with the check that it closes over; in your case, the check that's the argument to your createButton function for the call generating the button.

Or use addEventListener unless legacy support (IE8 and earlier, including IE's [in]compatibility mode) is required:

btn.addEventListener("click", function() {
    return checkQuestion(check);
}, false);