I have a razor syntax like this:
foreach(var item in model)
{
<td><a href ="#" onclick="Getinfo(@item.email);" >6/16/2016 2:02:29 AM</a> </td>
}
My javascript that recieves the request goes like this:
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
function Getinfo(elem) {
var email = document.getElementById(elem).innerHTML;
}
</script>
When clicking on the href link, I get the following error in the console of the browser:
«Uncaught SyntaxError: Invalid or unexpected token»,
and this part is underlined:
**</a> </td>**
I am a beginner so I get stuck in syntax a lot. If it is that then please help me out.
Satpal
132k13 gold badges160 silver badges168 bronze badges
asked Jun 16, 2016 at 11:50
You should pass @item.email in quotes then it will be treated as string argument
<td><a href ="#" onclick="Getinfo('@item.email');" >6/16/2016 2:02:29 AM</a> </td>
Otherwise, it is treated as variable thus error is generated.
answered Jun 16, 2016 at 11:53
SatpalSatpal
132k13 gold badges160 silver badges168 bronze badges
1
The accepted answer work when you have a single line string(the email) but if you have a
multiline string, the error will remain.
Please look into this matter:
<!-- start: definition-->
@{
dynamic item = new System.Dynamic.ExpandoObject();
item.MultiLineString = @"a multi-line
string";
item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
function Getinfo(text) {
alert(text);
}
</script>
Change the single-quote(‘) to backtick(`) in Getinfo as bellow and error will be fixed:
<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>
answered Jan 5, 2019 at 13:20
Iman BahrampourIman Bahrampour
6,1802 gold badges41 silver badges64 bronze badges
I also had an issue with multiline strings in this scenario. @Iman’s backtick(`) solution worked great in the modern browsers but caused an invalid character error in Internet Explorer. I had to use the following:
'@item.MultiLineString.Replace(Environment.NewLine, "<br />")'
Then I had to put the carriage returns back again in the js function. Had to use RegEx to handle multiple carriage returns.
// This will work for the following:
// "hello\nworld"
// "hello<br>world"
// "hello<br />world"
$("#MyTextArea").val(multiLineString.replace(/\n|<br\s*\/?>/gi, "\r"));
answered Mar 26, 2019 at 11:14
cspetecspete
1708 bronze badges
I have a razor syntax like this:
foreach(var item in model)
{
<td><a href ="#" onclick="Getinfo(@item.email);" >6/16/2016 2:02:29 AM</a> </td>
}
My javascript that recieves the request goes like this:
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
function Getinfo(elem) {
var email = document.getElementById(elem).innerHTML;
}
</script>
When clicking on the href link, I get the following error in the console of the browser:
«Uncaught SyntaxError: Invalid or unexpected token»,
and this part is underlined:
**</a> </td>**
I am a beginner so I get stuck in syntax a lot. If it is that then please help me out.
Satpal
132k13 gold badges160 silver badges168 bronze badges
asked Jun 16, 2016 at 11:50
You should pass @item.email in quotes then it will be treated as string argument
<td><a href ="#" onclick="Getinfo('@item.email');" >6/16/2016 2:02:29 AM</a> </td>
Otherwise, it is treated as variable thus error is generated.
answered Jun 16, 2016 at 11:53
SatpalSatpal
132k13 gold badges160 silver badges168 bronze badges
1
The accepted answer work when you have a single line string(the email) but if you have a
multiline string, the error will remain.
Please look into this matter:
<!-- start: definition-->
@{
dynamic item = new System.Dynamic.ExpandoObject();
item.MultiLineString = @"a multi-line
string";
item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
function Getinfo(text) {
alert(text);
}
</script>
Change the single-quote(‘) to backtick(`) in Getinfo as bellow and error will be fixed:
<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>
answered Jan 5, 2019 at 13:20
Iman BahrampourIman Bahrampour
6,1802 gold badges41 silver badges64 bronze badges
I also had an issue with multiline strings in this scenario. @Iman’s backtick(`) solution worked great in the modern browsers but caused an invalid character error in Internet Explorer. I had to use the following:
'@item.MultiLineString.Replace(Environment.NewLine, "<br />")'
Then I had to put the carriage returns back again in the js function. Had to use RegEx to handle multiple carriage returns.
// This will work for the following:
// "hello\nworld"
// "hello<br>world"
// "hello<br />world"
$("#MyTextArea").val(multiLineString.replace(/\n|<br\s*\/?>/gi, "\r"));
answered Mar 26, 2019 at 11:14
cspetecspete
1708 bronze badges
Are you dealing with uncaught syntaxerror: invalid or unexpected token error message while working with JavaScript?
And you’re struggling with how you are going to troubleshoot this error? Well, you just have to keep on reading!
In this article, we’ll explore how to fix the syntaxerror: invalid or unexpected token error message in JavaScript.
The error message uncaught syntaxerror: Invalid or unexpected token occurs when there is a problem with the syntax of your code.
This error indicates that the JavaScript interpreter encounters an unexpected token. This unexpected token could be a misplaced punctuation mark, a misspelled keyword, or any other element that violates the syntax rules of JavaScript.
Moreover, this error occurs when a specific language construct was expected, but you provide something else.
Why does “invalid or unexpected token” SyntaxError occur?
This error message can occur because of several factors. Some of the factors why does this error raise includes the following:
❌ Missing or extra brackets {}, parentheses (), or commas(,) in your code.
❌ Missing closing quote of a string literal, or some unnormal characters in the JavaScript code.
❌ Improper Usage of Keywords or Reserved Words.
❌ Forget to close a script tag and points to an incorrect path.
How to fix “uncaught syntaxerror: invalid or unexpected token”?
To fix the uncaught syntaxerror invalid or unexpected token error, check the data to be displayed on the page and add quotes to the strings or encrypt the strings. Also, check your code for any missing or extra brackets, parentheses, or commas.
Solution 1: Ensure script tags are in the correct paths
For example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script
</script>
</head>
<body></body>
</html>
Solution 2: Check for invalid characters
You may have an invalid character in your code for instance, directly after a curly bracket.
You can try copying the code into your browser console to see if there are any red dots it indicates invalid characters.
Solution 3: Ensure you don’t have extra or missing or brackets, parentheses and commas
Example 1:
for (let a = 0; a < 10; ++i) {
console.log(a);
}}
As you can see, there’s an extra bracket, so to fix the error, we just simply remove it.
Corrected code:
✅for (let a = 0; i < 10; ++i) {
console.log(a);
}
Example 2:
const samplearr = [10, 20, 30, 40, 50]]
In this example, we can see that there’s an extra square bracket, the same thing we should do. We have to remove the extra square bracket to resolve the error.
Corrected code:
✅ const samplearr = [10, 20, 30, 40, 50]
Example 3:
const samplearr = ['x', 'y' 'z']
Here, we can see that there’s a missing comma, so to resolve this error, we need to put a comma(,).
Corrected code:
✅ const samplearr = ['x', 'y', 'z']
Example 4:
const sample str = "itsourcecode.com
Here, we forgot to put the missing double quote. To resolve it, we need to put the missing end quote(“).
Corrected code:
✅const str = "itsourcecode.com"
Conclusion
In conclusion, the error message uncaught syntaxerror: Invalid or unexpected token occurs when there is a problem with the syntax of your code.
This error indicates that the JavaScript interpreter encounters an unexpected token. This unexpected token could be a misplaced punctuation mark, a misspelled keyword, or any other element that violates the syntax rules of JavaScript.
This article already discussed what this error is all about and multiple ways to resolve this error.
By executing the solutions above, you can master this Syntaxerror with the help of this guide.
You could also check out other “SyntaxError” articles that may help you in the future if you encounter them.
- Syntaxerror: cannot assign to function call
- Syntaxerror invalid character in identifier
- Multiple statements found while compiling a single statement
We are hoping that this article helps you fix the error. Thank you for reading itsourcecoders 😊
I Include an external javascript file in an Html file, when I browse the Html file in a web browser, I meet the javascript error with the error message Uncaught SyntaxError: Invalid or unexpected token. This article will tell you how to fix it.
1. How To Reproduce The JavaScript Uncaught SyntaxError: Invalid Or Unexpected Token.
- The Html file name is test.html.
- In the test.html file, it imports an external javascript file test.js using the below code.
<script type="text/javascript" src="test.js" ></script>
- Open the Html file test.html in the Google Chrome web browser.
- Right-click the web page in the web browser, then click the Inspect menu item in the popup menu list to open the web browser Inspector window.
- Click the Console tab on the web browser’s Inspector window.
- Then you can see the error message Uncaught SyntaxError: Invalid or unexpected token in the console output.
2. How To Fix The JavaScript Uncaught SyntaxError: Invalid Or Unexpected Token.
- The main reason for such error is because there are some unnormal characters in the javascript code that are not encoded in the correct charset.
- You just need to remove the javascript code in the error line, and to see whether the error disappears.
- Do not forget to refresh the test.html and the test.js file to make the change take effect.
- You can also copy the javascript code line that has the error occurs to the text editor such as Sublime Text.
- Then you can find the unnormal character in it and remove it to fix the error.
<0x200b>// Create a SnowFlakeApp instance when the window is loaded. window.onload = new SnowFlakeApp();
- In the above example javascript code, the character <0x200b> is unnormal, remove it then you can fix the error.
Когда встречается. Допустим, вы пишете цикл for на JavaScript и вспоминаете, что там нужна переменная цикла, условие и шаг цикла:
for var i = 1; i < 10; i++ {
<span style="font-weight: 400;"> // какой-то код</span>
<span style="font-weight: 400;">}</span>
После запуска в браузере цикл падает с ошибкой:
❌ Uncaught SyntaxError: Unexpected token ‘var’
Что значит. Unexpected token означает, что интерпретатор вашего языка встретил в коде что-то неожиданное. В нашем случае это интерпретатор JavaScript, который не ожидал увидеть в этом месте слово var, поэтому остановил работу.
Причина — скорее всего, вы пропустили что-то из синтаксиса: скобку, кавычку, точку с запятой, запятую, что-то подобное. Может быть, у вас была опечатка в служебном слове и язык его не распознал.
Что делать с ошибкой Uncaught SyntaxError: Unexpected token
Когда интерпретатор не может обработать скрипт и выдаёт ошибку, он обязательно показывает номер строки, где эта ошибка произошла (в нашем случае — в первой же строке):
Если мы нажмём на надпись VM21412:1, то браузер нам сразу покажет строку с ошибкой и подчеркнёт непонятное для себя место:
По этому фрагменту сразу видно, что браузеру не нравится слово var. Что делать теперь:
- Проверьте, так ли пишется эта конструкция на вашем языке. В случае JavaScript тут не хватает скобок. Должно быть for (var i=1; i<10; i++) {}
- Посмотрите на предыдущие команды. Если там не закрыта скобка или кавычка, интерпретатор может ругаться на код немного позднее.
Попробуйте сами
Каждый из этих фрагментов кода даст ошибку Uncaught SyntaxError: Unexpected token. Попробуйте это исправить.
if (a==b) then {}
function nearby(number, today, oneday, threeday) {
if (user_today == today + 1 || user_today == today - 1)
(user_oneday == oneday + 1 || user_oneday == oneday - 1)
&& (user_threeday == threeday + 1 || user_threeday == threeday - 1)
return true
else
return false
}
var a = prompt('Зимой и летом одним цветом');
if (a == 'ель'); {
alert("верно");
} else {
alert("неверно");
}
alert(end);


