I'm struggling with a complex nested quotes statement here :
var name = "foo";
$("#list").append("<li data-theme='c'><a href='#details' onclick='sessionStorage.name=PRINT_VAR_NAME_HERE;' data-transition='slide'>PRINT_VAR_NAME_HERE</a></li>");
I am able to print the variable's value fine in the second position by using : "+name+"
But not sure how to get it done in the first position.
(I have used 'PRINT_VAR_NAME_HERE' as a placeholder for the first and second positions)
Any ideas ? Thanks.
Just use the string-delimiters (the ") to break the string and concatenate the string with your variable, and escape (with the backslash) any quotes that you need to appear in the string itself:
$("#list")
.append("<li data-theme='c'><a href='#details' onclick='sessionStorage.name=\"" + name + "\"' data-transition='slide'>"+ name + "</a></li>");
I am, of course, assuming that you want to quote the variable in the string, otherwise I couldn't see what the problem would be.
I was running into the same issue of trying to figure out how to nest quotes in a javaScript in order to generate HTML. I was hitting a particular snag in the 'onclick' area because I was including a variable within it. In addition, the browser was interpreting my quotes incorrectly.
The solution: You have to explicitly tell the browser which quotes you ARE using and where. And you do this by using ' for single-quote, and " for double-quotes.
Hopefully this is helpful to someone...
document.getElementById("item-controls-" + id).innerHTML = "<span class=\'controls\' id=\'save-control\' onclick='saveForm(\"" + id + "\")'>save</span> ...
Related
I need to escape single quotes in JavaScript function parameters to avoid this:
onclick="Javascript:INSERT_PRODUCT('188267','WILL AND GRACE','32311','L'ANNIVERSARIO DINOZZE ','20101113|04|18|','13/11/2010 0.00.00','CANALE 5 ',this);"
But I need to escape them inside a function call since I do not know the values that will be passed (db variables I can't escape from the database).
Is there a function that allows me to do something like the following?
onclick="Javascript:function(escape(param1), escape(param2), escape(param3));"
JSON.stringify(plainTextStr).replace(/&/, "&").replace(/"/g, """)
will produce a string you can safely embed in a quoted attribute and which will have the same meaning when seen by the JavaScript interpreter.
The only caveat is that some Unicode newlines (U+2028 and U+2029) need to be escaped before being embedded in JavaScript string literals, but JSON only requires that \r and \n be escaped.
Escape the apostrophe with a backslash:
onclick="INSERT_PRODUCT('188267','WILL AND GRACE ','32311','L\'ANNIVERSARIO DI NOZZE ','20101113|04|18|','13/11/2010 0.00.00','CANALE 5 ',this);"
It's maybe not totally clear from the question, but assuming that all you want is to send this to a PHP script for storing in a database, you of course would ideally utilize PHP's various methods such as stripslashes() -- but if you're really not trying to get too fancy, simply adding 1 slash in front of any single quote is enough to send a SQL query right into PHP from the client-side. It's not safe, but maybe not necessary either.
str.replace(/'/g, "\\'"); // escaping \ with \, so used 2x
does the trick., like for example in something like this:
var body = $('#body').val().replace(/'/g, "\\'");
myCustomSQLqueryFunction("UPDATE mytable SET `content`='"+ body +"';" );
MySQL will now store your body like you see it in the form field.
This function worked for me (it removes and restores the quote again):
Guessing that the data to be sent is the value of an input element,
var Url = encodeURIComponent($('#userInput').val().replace("'","\\'"));
Then get the original text again:
var originalText = decodeURIComponent(Url);
var cmpdetail = cmpdetail.replace(/'/g, "\\'");
its working for me.
I prefer to use single quote for defining JavaScript strings. Then I escape my embedded double quotes as follows.
This is how I do it, basically str.replace(/[\""]/g, '\\"').
var display = document.getElementById('output');
var str = 'class="whatever-foo__input" id="node-key"';
display.innerHTML = str.replace(/[\""]/g, '\\"');
//will return class=\"whatever-foo__input\" id=\"node-key\"
<span id="output"></span>
I encountered a similar issue recently, and solved it by replacing the single quote with the corresponding unicode (')
Initially my code was this, resulting in me getting results that were cut off (e.g. Jane's Coffee became just Jane in the output).
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
When I introduced unicode replacement (shown below), I got the exact output I wanted
b.innerHTML += "<input type='hidden' value='" + arr[i].replace("'", "'") + "'>";
I am trying to pass a string value from c# file to js file.
If I try to pass an int value, then I can pass it, but I am unable to pass string value.
string value = "abc";
int a=5;
TableCell.Attributes.Add("onclick", "F1("+value +")"); //NOTHING HAPPENS
TableCell.Attributes.Add("onclick", "F1("+a +")"); //Works Perfectly
js file
function F1(value) {
alert(value);
}
Pass string value in quotes ''
Use
TableCell.Attributes.Add("onclick", "F1('"+value +"')");
^ ^
Otherwise it treated as variable. Currently you must be getting error in browser console.
Consider what your HTML will look like.
First version:
onclick="F1(abc)"
Second version:
onclick="F1(5)"
Clearly the second version is passing the value 5. The first version is passing the value of abc - whatever that is, within the context of the Javascript you're executing.
You could quote the string, making sure that you escape quotes etc - I'm assuming that in reality, your value is fetched dynamically from somewhere, and you might not have much control over the content. Hopefully there's something within whatever ASP.NET version you're using that will let you do that, such as HttpUtility.JavaScriptStringEncode.
For example, to get the string abc in your call, you want the attribute to be:
onclick="F1('abc')"
but if to get the string I don't know in your call, you want the attribute to be:
onclick="F1('I don\'t know')"
The key is to look at the generated HTML - pretend you're the browser, and look at the world from its perspective. Once you've worked out what HTML you want to generate, writing the code to do so is often relatively simple.
Try adding single-quotes around the value when building it in your C# string. In your first scenario, the Js is receiving:
F1(abc);
Which it reads as being the variable abc. Try adding single quotes (and it's probably best to use string.format, BTW):
TableCell.Attributes.Add("onclick", string.Format("F1('{0}')", value));
When you use the string, it would produce the JavaScript code F1(abc). That would interpret abc as a variable name, not a string literal.
Add apostrophes around the string to make it a string literal:
TableCell.Attributes.Add("onclick", "F1('" + value + "')");
If the string can contain apostrophes or backslashes, you would need to escape them:
TableCell.Attributes.Add("onclick", "F1('" + value.Replace("\\", "\\\\").Replace("'", "\\'") + "')");
This will take care of escaping any special characters (i.e. quotes, etc...)
TableCell.Attributes.Add("onclick", "F1('"+HttpUtility.JavaScriptStringEncode(value)+"')");
If you're passing a string through the argument, you need either " or ' characters to delimit it. Your variable name is translating to (adb) in the call. ("adb") or ('adb') would be the string value.
That's because it will print
F1(abc)
So it will look for a variable called abc.
You should use
TableCell.Attributes.Add("onclick", "F1(\""+value +"\")");
So the output will be
F1("abc")
I have a html page in which I need to pass a String variable to javascript function. This works until String does not have a special charecter.
<html>
<head>
<script>
function test(v){
alert(v);
}
</script>
</head>
<body>
<input type="button" value="Test Button" onClick="test('BlahBlah')"/>
</body>
</html>
As soon as I change onClick like below, it stops working.
onClick="test('Blah'Blah')"
Any solution for this problem. Please take a note parameter which is being passed to JavaScript function is dynamic.Source of Parameter is backend and I cannot change that peice of code. Second thing even if put escape it still does not work. My problem is I have to retian the special charecter for some processing at backend
There are two layers to this:
The content of onClick attributes, like all attributes, is HTML text. That means that any character that's special in HTML (like <) must be replaced with an HTML entity (e.g., <). Additionally, if you use double quotes around the attribute value, any double quotes within the value must be replaced with entities ("); if you used single quotes around the attribute, you'd need to replace ' with '.
Your attribute contains a JavaScript string literal. That means that any characters that are special inside JavaScript string literals must be escaped according to the JavaScript rules. Since you've used single quotes to delimit the JavaScript string, for instance, you have to escape any single quotes in the string with a backslash.
I'm assuming that HTML is generated server-side. If so, the work above must be done server-side, when building the HTML of the page. You haven't said what server-side tech you're using, so it's hard to point you at solutions that your server-side tech/environment might provide.
In the simple case of your
onClick="test('Blah'Blah')"
...you just need to add the backslash within the JavaScript string
onClick="test('Blah\'Blah')"
...but that's just that one specific case.
The dramatically simpler option is to not put JavaScript code in attribute values. Instead, use modern techniques (addEventListener, attachEvent) to hook up JavaScript code.
But if you must use an onClick attribute, avoid having text in it (or deal with the complexities above); have it call a function defined in a script element that then has the text, as you then have only the one layer (#2 above) to deal with.
Source of Parameter is backend and I cannot change that peice of code.
That backend is broken and needs fixing.
If:
the backend is only producing invalid JavaScript code (not invalid HTML)
and the code consists of a single function call
and the code is always a single function call
and the function call always has a single string literal argument
and that argument is always delimited with single quotes
and the single quotes within the string are never correctly escaped
...we might be able to salvage it client-side. But my guess is that the backend will also produce invalid HTML, for instance when the text has a " in it. (We can't do anything about that, because the attribute value will be chopped off at that point.)
But let's keep a good thought: Given the ridiculous list of caveats above, this might do it:
var elm = document.getElementById("the-div");
var code = elm.getAttribute("onclick");
var m = code.match(/^([^(]+)\('(.*)'\)$/);
if (m) {
code = m[1] + "('" + m[2].replace(/'/g, "\\'") + "')";
}
elm.setAttribute("onclick", code);
Live Example:
function foo(str) {
alert(str);
}
var elm = document.getElementById("the-div");
var code = elm.getAttribute("onclick");
var m = code.match(/^([^(]+)\('(.*)'\)$/);
if (m) {
code = m[1] + "('" + m[2].replace(/'/g, "\\'") + "')";
}
elm.setAttribute("onclick", code);
<div id="the-div" onclick="foo('blah'blah')">Click me</div>
Well this is an very common problem you wanted to add single quotes inside single quotes to do this you have to escape that Sigle quotes to do that you have to put an forward slash.
onClick="test('Blah\'Blah')"
I have a grid with link button and on RowDatabound:
lbutton.Attributes.Add("onclick",
"javascript:window.showModalDialog('Showsome.aspx?ID=" + lbutton.CommandArgument + " &IsMA=M" +
"','window.self','dialogWidth:800px; dialogHeight:800px;center:yes; status:yes; scroll:no; help:no');");
I am able to retrieve ID from Request.QueryString["ID"];
However, I am not able to retrieve Request.QueryString["IsMA"]
How can this be achieved?
I tried the suggestions, no more spaces and did URL encode and I am not getting the value correctly. I have another approach since it is a hardcoded value 'M' that is needed along with the value I am now appending it in ID value itself 'Showsome.aspx?ID=M" . Thanks for you support.
Theres a space between the CommandArgument and &IsMA
Could this be causing your problem?
Try:
+ lbutton.CommandArgument + "&IsMA=M"
What is CommandArgument value? You may need to encode this. I would recommend doing this either way.
+ Server.UrlEncode(lbutton.CommandArgument) + "&IsMA=M"
Try removing the space before the ampersand character:
lbutton.CommandArgument + "&IsMA=M"
EDIT: As SLaks points out below, escaping the ampersand character is not necessary. Accordingly, the documentation for Attributes.Add() says:
If the string in the value parameter contains an ampersand (&), the
character is automatically encoded. The resulting HTML representation
is "&".
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Difference between single quotes and double quotes in Javascript
Sorry guys, but here I am asking a stupid question.
In Javascript, do we use " or ' ?
Looking at the code below, it seems that " and ' behave differently?
var html = '<dt> <img src="' + imageurl + '" /> </dt>';
Can somebody explain to me the different between " and ' ?
In javascript there is no difference. Both are valid for enclosing a string i.e. defining a string literal.
Your example shows double quotation marks that are a value inside a string. They are clearly part of markup that is held in that string. Their presence is unrelated to the javascript language, and that string could equivalently have been defined:
var html = "<dt> <img src=\"" + imageurl + "\" /> </dt>";
Usually the only reason one is chosen over the other is convenience. For example, when quoting markup (as in your example) there are often many double quotes (although single quotes are just as valid), so it's easier to define the string with single quotes, and not have to escape slash every quote that should be part of the string (as oppose to defining the string's boundaries).
On the other hand, free text often contains many apostrophes, in which case it's often easier to enclose the string with double quotes: "It'll be easier this way, that'll save me some work".
It depends on what you open and close with.
A ' will end on the next detected ' and a " will end on the next detected "
Your example could also be written:
var html = "<dt> <img src='" + imageurl + "' /> </dt>";
There is no difference, it just depends on what you open with
You can use single or double quotes to enclose an expression. As long as the same type of quote closes the expression, all is good.
If you plan on including HTML in the string, you should use single quotes... that way you don't have to escape the double quotes.
If you used double quotes in the above, you would need to escape the inside quotes, eg.
var html = "<dt> <img src=\"" + imageurl + "\" /> </dt>";
In javascript, they are the same. You can switch between them for easier escaping of potential quotes in the string literal itself.
Be careful, because in some other languages (like perl) there is a difference: in that case, double quoted string would allow variable interpolation, while single quoted strings would not. Javascript at present does not support this feature.
You can use either form of quote. These are identical:
var html1 = "<bold>Hi</bold>";
var html2 = '<bold>Hi</bold>';
Whichever delimiter you choose to start the string with, the next unescaped occurrence of that delimiter signals the end of the string.
Where life gets interesting is when there are embedded quote marks in your string itself. For example, supposed you want to assign this to a javascript variable:
<img src="http://www.google.com/images/logo1w.png">
In that case, you a couple choices. You could use this which escapes the embedded double quotes:
var html1 = "<img src=\"http://www.google.com/images/logo1w.png\">";
or you can use this:
var html2 = '<img src="http://www.google.com/images/logo1w.png">';
I find that the latter looks a lot cleaner.