document.getElementById("img").innerHTML="< img src='/sitepath/"+imgg+".jpg' width='72' height='44' onclick='alert('hello');' />";
The above code is my javascript. Problem is printing hello or any other string. If I just type 123 in place of hello, it does give alert. But am not able to use a string like hello there. Normally a string in an alert function is kept inside quotes ' ' but the entire content is inside double quotes and I have already used single quote at the beginning of onclick function. I tried using Escape character ("\") but it didnt help. Any suggestions?
Try this:
document.getElementById("img").innerHTML = '<img src="/sitepath/' + imgg + '.jpg" width="72" height="44" onclick="alert(\'hello\');" />';
If you use apostrophes as delimiter for the HTML attributes, you have to HTML encode the apostrophes that you put inside the attribute:
document.getElementById("img").innerHTML="< img src='/sitepath/"+imgg+".jpg' width='72' height='44' onclick='alert('hello');' />";
I prefer using apostrophes as string delimited in Javascript and quotation marks as delimiters for HTML attributes. Then you just escape the apostrophes that you have inside the Javascript string:
document.getElementById("img").innerHTML='< img src="/sitepath/'+imgg+'.jpg" width="72" height="44" onclick="alert(\'hello\');" />';
To put any string inside a Javascript, inside an HTML attribute, inside a string in Javascript, you do:
escape any string delimiters in the string
HTML encode the Javascript code
escape any string delimiters in the HTML string
You have JavaScript inside HTML inside JavaScript. That's naturally confusing. Better to avoid the string-slinging problems of quoting and escaping (which, got wrong, can easily lead to security holes when user-submitted data is used), and do it the DOM way:
var img= new Image();
img.src= '/sitepath/'+imgg+'.jpg';
img.width= 72;
img.height= 44;
img.onclick= function() {
alert('hello');
};
document.getElementById('img').appendChild(img);
I tried using Escape character ("\") but it didnt help
Javascript is different from C#, you just use it twice at a time, example: alert('We are\\'t going to go')
It doesn't matter if your outer quotes are single or double. You can escape a character within an outer string with a backslash... \' becomes ' within the string itself. Either Darin's or Masood's example will work. But Masood is ignorant in reference to a need to use double-quotes as the outside enclosure.
what if someone needs to send a variable instead of a string "hello"? Something like this:
function showContent(toPopulate) {
document.getElementById(toPopulate).innerHTML = "<a href='javascript:showOtherContent(*toPopulate*);'>show</a>"
}
function showOtherContent(toPopulate) {...}
so how to send toPopulate as a variable to showOtherContent()?
The above is solved like this:
document.getElementById(toPopulate).innerHTML = "<a href='javascript:showOtherContent(\"" + toPopulate + "\");'>show</a>"
You will need to use the double quotes and escape it in the onclick attribute
document.getElementById("img").innerHTML="<img src='/sitepath/"+imgg+".jpg' width='72' height='44' onclick=\"alert('hello');\" />";
Related
I'm having some trouble trying to replace the single quotes ('...') with double quotes("...") in the following piece of code:
<img id="image" src="images/bird.jpg" onmouseover="PlaySound('mySound'); this.src='images/bird_second_frame.jpg'"
onmouseout="StopSound('mySound'); this.src='images/bird.jpg'">
Whenever I attempt to replace the single quotes with doubles, the code breaks, and I can't seem to find a different solution. I've been told not to use single quotes at all - is this an exception?
Any help is appreciated.
You can't use a literal " inside an HTML attribute value delimited by " characters. It will terminate the attribute value prematurely.
You can include one as ", but that would make the code significantly harder to read.
<img id="image" src="images/bird.jpg" onmouseover="PlaySound("mySound"); this.src="images/bird_second_frame.jpg"" onmouseout="StopSound("mySound"); this.src="images/bird.jpg"">
I've been told not to use single quotes at all - is this an exception?
No. You've just been given bad advice.
JavaScript and HTML don't distinguish between ' and " except when determining which characters can appear between them without being escaped.
Using ' in your example is simply more readable.
A better approach would be to avoid inline JavaScript entirely though.
<img id="image"
src="images/bird.jpg"
data-sound="mySound"
data-frame="images/bird_second_frame.jpg">
<script>
var element = document.getElementById("image");
element.addEventListener("onmouseover", play);
element.addEventListener("onmouseover", stop);
function play() {
PlaySound(this.dataset.sound);
this.dataset.original = this.src;
this.src = this.dataset.frame;
}
function stop() {
StopSound(this.dataset.sound);
this.src = this.dataset.original;
}
</script>
You can't use double quotes inside of a string that's bounded by double quotes because they would end the string.
Your use of single quotes looks appropriate in this case.
You can use single quotes freely in JavaScript; they're syntactically equivalent to double-quote characters (though any single string constant must be bound by the same kind of quote). That goes for HTML too, so you can get double quotes in your JavaScript by using single quotes for the attribute value delimiters:
<button onclick='alert("Hello World")'>Click Me</button>
However if you really want double quotes everywhere, you can escape them as HTML entities:
<button onclick="alert("Hello World")">Click Me</button>
That's pretty ugly but it works: the HTML parser is specifically looking for quote characters.
The best thing to do is to stop embedding your JavaScript event handler setup in your HTML and do it purely with JavaScript.
I have this line that appending this in jquery:
$('#league2').append("<input type=\"button\" id=\"2btn\" value=\"1.2\" class=\"butta\" onmousedown=\"active('exam\'ple','awayteam')");
Notice the "exam\'ple"... i escaped the ' with \'
so when clicking the button, the function active should work.
this is the function active:
function active(hometeam,awayteam){
alert("if this is alerted, it works!");
}
when i click the button it should alert "if this is alerted, it works!", but it's not alerting it. and it think because when i use the function, this is the outpot:
function active(exam\'ple,awayteam){
when i appending the same thing with a word that does not contain " ' ", it is working.
You need to escape the backslash in your parameters for the active function, instead of the apostrophe.
$('#league2').append("<input type=\"button\" id=\"2btn\" value=\"1.2\" class=\"butta\" onmousedown=\"active('exam\\'ple','awayteam')");
To escape a string to append it to that code with php, you can use regular expressions. The following will work in your case.
// Replaces a backslash with four backslashes: The 'append' function will interpret it as two backslashes; the 'active' function, as only one.
$str = preg_replace("/\\\\/", "\\\\\\\\\\\\\\\\", $str);
// Replaces an apostrophe with two backslashes and an apostrophe, then javascript will append only one backslash and an apostrophe, escaping that way an apostrophe.
$str = preg_replace("/'/", "\\\\\\\\'", $str);
// Replaces quotations with a backslash and quotations: the quotations will be escaped inside the append function, so one quotations will be printed out on your HTML
$str = preg_replace("/\"/", "\\\\\"", $str);
If you don't know what a regular expression (regex) is, I suggest you researching a bit about how to use them. They will help you a lot.
EDIT: By some reason, the last program needed double of backslashes to work. Updated.
You don't need to escape single quotes when the string is double-quoted. It's best practice to wrap the whole string in single quotes, allowing you to use double quotes without the need to escape. (or single quotes with it all wrapped up in doubles).
For example:
$("#thing").append('<div id="foo" class="bar" style="color:black;" onclick="foobar()"></div>');
Your code's a little more complicated, because there's multiple levels (have you considered jQuery's click?):
$('#league2').append('<input type="button" id="2btn" value="1.2" class="butta" onmousedown="active('exam\'ple','awayteam')');
onclick= "_deleteWPSchemeData(${viewWPMasterGrid.id}, '${viewWPMasterGrid.name}')"
${viewWPMasterGrid.name} retutrns me a string(for e.g. W.P.WINT OFF ALL'10) which often has single quote character so from the calling javascript method I am not getting the second parameter at all. How to deal with problem?
When a dynamic String can be put inside a JavaScript string literal, it should be JS-escaped. Just as when a dynamic String is put inside a HTML page, it's HTML-escaped.
Use commons-lang StringEscapeUtils.escapeECMAScript (or escapeJavaScript depending on the version) to escape the String. You could create a very simple EL function to do that straight from the JSP.
Note that you could have problems with single quotes, but also double quotes, tags, EOLs, backslash, which must all be escaped in a JS String literal.
It looks like you could split the second parameter out into its own variable first. If I have understood your question correctly.
var viewWPMasterGridName = "${viewWPMasterGrid.name}";
onclick = "_deleteWPSchemeData(${viewWPMasterGrid.id},'" + viewWPMasterGridName + "')";
Use '${viewWPMasterGrid.name.replaceAll("'", "\'")}'
try this,
var name = "${viewWPMasterGrid.name}".replace(/'/g,"\\'");
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.
I'm trying to pass a string like this:
{"key":["value"],"key2":undefined,"key3":undefined,"key4":undefined,"key5":"value"}
to a javascript-function like this:
<a href="#" onClick="myFunction(myString);">
but can't get the escaping right. Is there a way to pass that object-string to a function or do I need to convert something?
Greetings,
Select0r
try:
var myString = '{"key":["value"],"key2":undefined,"key3":undefined,"key4":undefined,"key5":"value"}';
EDIT:
In light of your recent comment I went back to the browser and tried this (works for me):
<a href="#" onClick="myFunction({'key':['value'],'key2':undefined,'key3':undefined,'key4':undefined,'key5':'value'});">
The change means that it's no longer longer passed as a string but as an object parameter to myFunction.
As Naeem said, you can enclose the string in a single quote. The difference between the single and double quote is this:
single quotes:
Can contain double quotes without stopping string
Cannot contain characters such as break lines
Can contain single quotes via \'
double quotes:
Can contain single quotes without stopping string
Can contain break line and other special characters
Can contain double quotes via \"
I found a solution, Naeem Sarfraz put me on the right track - it's not going to win a beauty contest, but it works:
As I can execute PHP in the context I'm in (but IE6 would ignore Javascript), I did a couple of replacements on single/double quotes with PHP.
$data = stripslashes(unserialize($data));
$data = addcslashes($data, "'");
$data = str_replace('"', "'", $data);
This will strip all slashes, add slashes for single quotes only and finally replace double quotes with single ones.
Now myString is in a state that can be passed to a Javascript function in onclick without quote-conflicts:
<a href="#" onClick="myFunction(<?php print $data; ?>);">
Thanks for your contributions!
If you can generate code just before this <a> element, you can try this:
<script type="text/javascript">
var myObj = {"key":["value"], "key2":undefined, "key3":undefined, "key4":undefined, "key5":"value"};
</script>
<a href="#" onClick="myFunction(myObj)">