Search code examples
javascriptunexpected-token

Why I keep getting an "unexpected token" error on this line of code?


Im using PHP to output rows of information. Im trying to add a hide/show to each row. I "ID" the row and then added a simple text "Hide/Show" button that references the ID'd row and attempts to toggle the "display" property.

Ive tried escaping the quotes, changing them to single quotes, adding/removing brackets. Im at a loss.

echo "<table width=\"640\" style=\"margin-left: auto; margin-right: auto;\"><tr id=\"JEntry".$data['ID']."\" style=\"display: visible\"><td><button onmousedown=\"javascript: if (document.getElementById(\"JEntry".$data['ID']."\").style.display != \"visible\") { document.getElementById(\"JEntry".$data['ID']."\").style.display = \"visible\"; } else { document.getElementById(\"JEntry".$data['ID']."\").style.display = \"none\"; }\">Hide or Show</button>";

Unexpected Token "}"


Solution

  • Your PHP code is fine. However, the generated HTML need to have its attributes escaped.

    For instance, your code outputs something like

    <button onmousedown="javascript: if (document.getElementById("JEntry")) {}"></button>
    

    As you can hopefully see, the quotes in the javascript match the quotes for the attribute value. This will result in parsing issues.

    To get around this either use single quotes in just the javascript

    <button onmousedown="javascript: if (document.getElementById('JEntry')) {}"></button>
    

    or escape them.

    <button onmousedown="javascript: if (document.getElementById(\"JEntry\")) {}"></button>
    

    In my opinion, the first option looks tidier, especially if you consider needing to escape the back-slashes (\). So your fixed code would be

    echo "<table width=\"640\" style=\"margin-left: auto; margin-right: auto;\"><tr id=\"JEntry".$data['ID']."\" style=\"display: visible\"><td><button onmousedown=\"javascript: if (document.getElementById('JEntry".$data['ID']."').style.display != 'visible') { document.getElementById('JEntry".$data['ID']."').style.display = 'visible'; } else { document.getElementById('JEntry".$data['ID']."').style.display = 'none'; }\">Hide or Show</button>";
    

    The way to read this is unescaped double quotes (") are part of your PHP, escaped double quotes (\") part of your HTML, and single quotes (') part of your JS.