Carlos F Carlos F - 7 months ago 21
Javascript Question

Unexpected token } at html tag

While using php, and doing several things I append this code to a HTML tag:

$tmp = $result[$i]['name'];
echo '<p><a href="#" onClick="setFood("'.$temp.'")"><b>'.$tmp.'</b></a></p>';


here is the setFood function

function setFood(food){
localStorage.clear();
localStorage.setItem('currentFood', food);
window.location.replace("food_specification.html");
}


I get the error:

Uncaught SyntaxError: Unexpected token }


and it redirects me to this:

(function(event){setFood(
})


Marking the error at the second line. and somethings it redirects to the
html
tag.
Also if I remove the href and the function that I want to use it works:

echo '<p><a href="food_specification.html"><b>'.$tmp.'</b></a></p>';


Any idea what the problem can be? All the js are being implemented correctly.

Answer

Your output will be onClick="setFood("temp")",try below: echo '<p><a href="#" onClick="setFood(\''.$temp.'\')"><b>'.$tmp.'</b></a></p>';