Javascript SyntaxError: Unexpected Token '}'

- 1 answer

I have the following simple code, however for some reason it trows a Unexpected token "}" error, and I'm not entirely sure why. I have the following code to generate the buttons

var OverlayMessage = ("Do you want to test these settings? <br> <h6>" + protocol + ":" + systemcodeSend + "-" + unitcode + " sending " + state + '</h6> <br> <a id="btnGreen" onclick="checkIfSettingsWork("' + protocol +'", "'+ systemcodeSend +'", "'+ unitcode +'", "'+ state +'");">Yes</a> <a id="btnRed" onclick="toggleVisibility(\'overlayAddDevice\')">No</a>');

The output of console.log is as followed

<a id="btnGreen" onclick="checkIfSettingsWork("pollin", "31", "14", "on");">Yes</a>

The strange thing is, if I run from the debugger, it works fine without errors. However when being ran trough the onclick event it trows the Unexpected token error.

The function checkIfSettingsWork is not even being ran, I checked this by letting it log to console, and that is returning nothing when being ran by the onclick event however it works when I run the following javascript trough the debugger.

checkIfSettingsWork("pollin", "31", "14", "on");

This is the checkIfSettingsWork function.

function checkIfSettingsWork(protocol, systemcodeSend, unitcode, state) {
    console.log(protocol + systemcodeSend + unitcode + state)



This is invalid html:

 <a id="btnGreen" onclick="checkIfSettingsWork("pollin", "31", "14", "on");">Yes</a>

The " characters are ending your onclick attribute early, so the browser ends up interpreting it as just onclick="checkIfSettingsWork(".

Change it to this for a workaround:

<a id="btnGreen" onclick="checkIfSettingsWork('pollin', '31', '14', 'on')">Yes</a>