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.
3 Answers
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.
1The 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> 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"));