I am trying to directly write a Javascript variable assignment code on a ASP.NET web page.
Response.Write("<script>itHtml = '");
Response.Write("<div id=\"pop_ctrl\">Select</div><ul id=\"demo_ul\">");
foreach (Article a in arts)
{
Response.Write("<li class=\"demo_li\"><a onclick=\"ShowArticleCard(" + a.Id + ",\'" + a.User + "\',\'" + a.DateString + "\'); return false\"><div>" + it.User + "</div> <div>" + it.Title + "</div></a></li>");
}
Response.Write("</ul>");
Response.Write("';</script>");
Anchor tag in this markup executes a function ShowArticleCard() on click. This function accepts one int and two string parameters. When I am trying to add a C# string variable in place of string parameters, it replaces them like a JavaScript keyword. I tried using ',\' and \", but error persists. So, are there any levels of nested quotes we can use? If not how can I resolve this?
Try wrapping the actual value (parameter) in the quotes, like this,
onclick=\"ShowArticleCard(" + a.Id + ",'" +
a.User + "','" + a.DateString + "'); // Remaining code
Changed
I have removed the single quotes from the int type param, and removed the escape slash from the string types. They can be simply put as, '. Now when the code would run, it would be considered as a string. Otherwise (if the value is numeric) then ignore these quotes and enter them as they are. Only string-type data requires to be wrapped in either ' or ". In JavaScript they are same. In C#, ' and " have different meanings, you know that well.
Tip: Also, if you are writing something for client-side rendering, like in ASP.NET, you can easily write it as,
string.Format("<a href='{0}' onclick='func({1})'>My Link</a>",
hyperlink, param);
This would be rendered as you want it to be. :) The single quotes would be converted to double quotes once rendered in your browser. Or you can use # before the string, and write " inside the string without having to escape them.
I figured out a way of doing this. I don't know why it didn't came in my mind before.
I enclosed JavaScript function's string parameters with \\'. Like this:
ShowArticleCard(" + a.Id + ",\\'" + a.User + "\\',\\'" + a.DateString + "\\');
So that the resultant code will be:
ShowArticleCard(someid,\'someUser\',\'someDateString\');
Related
I am trying to create an OData filter in AngularJS that gets the variables passed from my view.
I am struggling with the concatenation. Especially with the start and end quotes ". I researched and tried various options like adding \ etc., but no luck.
The hard-coded filter would look like this:
$filter: "contains(ProductCode, 'GDN') and Price ge 5 and Price le 20"
Here is my filter using variables passed from the view:
var newFilter = "contains(ProductCode, " + "'" + vm.codeO + "')" + " and Price ge " + vm.priceGtO + " and Price le " + vm.priceLtO "\""
My filter using the variable must look exactly the same. Including the start and end quotes ".
Thank you in advance!
You need to remove the ending "\"".
The string that you want to output is foo and not foo".
My filter using the variable must look exactly the same. Including the start and end quotes (").
That's your error. The start and end quotes were used just to say that the inner content is a string. You don't need to add extra quotes if you already have a string variable.
Also, you've added some additional concatenations that were not necessary. Try this:
var newFilter = "contains(ProductCode, '" + vm.codeO + "') and Price ge " + vm.priceGtO + " and Price le " + vm.priceLtO
this line:
return '<a href="javascript:SomeFunction('+ var1 + ',' + var2 + ')"; > Stars </a>';
renders this:
Stars
which looks like a proper anchor tag but gives this error on clicking it:
Uncaught SyntaxError: missing ) after argument list
I am sure this error is misleading as the bracket in question is right there.
What am I missing?
Thanks in advance.
As var1 contains a string value, you need quotes around it:
return ' Stars ';
If the string can contains characters that needs to be escaped to be in a string literal, or needs to be URI encoded, you need some more code:
return ' Stars ';
Generating code like this is complicated, and it's easy to get it wrong. If possible you should generate elements instead, so that you can set the properties directly instead of creating code for it. Example using jQuery:
return $('<a>', { href: '#', text: ' Stars ' }).click(function(e){
e.preventDefault();
SomeFunction(var1, var2);
});
You have mistake in double quote at the end
return '<a href="javascript:SomeFunction('+ var1 + ',' + var2 + ');" > Stars </a>';
You are not wrapping your first var (which seems to be a string) within quotes.
return '<a href="javascript:SomeFunction(\''+ var1 + '\', ' + var2 + ');" > Stars </a>';
NOTE: As pointed out in the comments by Paul S. the semicolon should be inside the double quotes as it is part of the attribute value.
As you just want to add an <a> with a href, let the browser do the escaping and encoding work for you by using a method like String.prototype.link
' Stars '.link('javascript:SomeFunction(' + JSON.stringify(var1) + ', ' + JSON.stringify(var2) + ')');
// Stars
If you're running into issues like this a lot, consider whether it would be easier to switch to working with DOM methods, i.e.
var a = document.createElement('a');
a.addEventListener('click', SomeFunction.bind(a, var1, var2));
This saves you from having to write entity encodings etc to protect yourself at each level the code will be interpreted (JavaScript, HTML, JavaScript) and means you have more direct access over the DOM tree than by writing HTML
I want to put "</script>" in a variable in JavaScript but it will be consider as end tag like below example:
<script>
content.value = aval + '<script> ma_gallery("' + varimgurl + '");</script>'+ sevom;
</script>
Does anyone know a solution ?
Use '<\/script>'.
In a string literal, an escaped slash is equivalent to a slash so it makes no difference to the JavaScript parser but it breaks up the end tag syntax so it isn't parsed as an end tag by the HTML parser.
(An alternative is to split it up into two strings and concatenate them together, but that is more typing, harder to read, and (albeit not significantly) less efficient).
Split "</script>" into two strings:
content.value = aval + '<script> ma_gallery("' + varimgurl + '");</scr' + 'ipt>' + sevom;
Here, while calling a function displayCDinfo(), the syntax used is
document.write("<tr onclick='displayCDInfo(" + i + ")'>");
where i is the for loop counter.
However, the function declaration is given as
function displayCDInfo(i)
{
...
}
Why do they use displayCDinfo(" + i + ") instead of displayCDinfo(i) while calling the function? The code doesn't work when the "+ +" is removed.
The + operator is joining the variable's value to the string. Otherwise you are sending the letter i instead of what i contains.
It's all about the quotes. In the first instance, it's escaping the string to allow i to be sent as a variable instead of a character
C# Code
string excerpt = " <a href='#' onclick='javascript:onOptionSelect(" + pat.PatientId + "," + pat.PatientName.Replace(",", "") + "," + pat.PatientDob + ",1" + ")'>Patient Chart</a>";
I need to pass the string values pat.PatientName and pat.PatientDob in single quotes to java script function. I tried many ways but i am not able to find out the right way of passing values.