Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript in html - Using single quote inside another single quote

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?

like image 543
Ashish Nair Avatar asked Jan 08 '10 09:01

Ashish Nair


4 Answers

Try this:

document.getElementById("img").innerHTML = '<img src="/sitepath/' + imgg + '.jpg" width="72" height="44" onclick="alert(\'hello\');" />';
like image 157
Darin Dimitrov Avatar answered Oct 13 '22 23:10

Darin Dimitrov


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(&#39;hello&#39;);' />";

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
like image 28
Guffa Avatar answered Oct 13 '22 21:10

Guffa


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);
like image 35
bobince Avatar answered Oct 13 '22 22:10

bobince


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')

like image 45
MA9H Avatar answered Oct 13 '22 22:10

MA9H