2

Hi I had a similar requirement as below and was curious to know to fix the issue.

Below is the code

<script type="text/javascript">
function Msg1(){
  var sd= document.getElementById('myText').innerHTML = 'Thank's!';
  alert('-sd-'+sd);
}
function Msg2(){
  document.getElementById('myText').innerHTML = 'Try messages 1 again...';
}
</script>
<input type="button" onclick="Msg1()" value="Show Message 1" />
<input type="button"  onclick="Msg2()" value="Show Message 2" />
<p id="myText"></p> 

The innerHTML tag is throwing script error like

Webpage error details


Message: Expected ';'
Line: 29
Char: 64
Code: 0
URI: file:///C:/Documents%20and%20Settings/j1007962/Desktop/spl.html

I was looking for the fix around innerHTML or better replace with something which would fix this . Thanks

GustyWind
  • 3,026
  • 3
  • 41
  • 50
  • I dont want to replace the message in double quotes as this is dynamically generated one – GustyWind Aug 01 '11 at 06:46
  • This may help for dynamically generated one http://stackoverflow.com/questions/97578/how-do-i-escape-a-string-inside-javascript-inside-an-onclick-handler – nidhin Aug 01 '11 at 06:57

2 Answers2

7

You should escape your quotes.

Modify

var sd= document.getElementById('myText').innerHTML = 'Thank's!';

To

var sd= document.getElementById('myText').innerHTML = 'Thank\'s!';

Or use double quotes

var sd= document.getElementById('myText').innerHTML = "Thank's!";
nidhin
  • 6,661
  • 6
  • 32
  • 50
1

Try to escape the single quote

var sd= document.getElementById('myText').innerHTML = 'Thank\'s!';

Edit

Let say we have some text coming from Server side or from a HTML tag. In that case we have a valid variable. So there is no need to change that variable.

<div id="div1">
    Thank's!
</div>

<script language="javascript" type="text/javascript">

function changeDivHTML()
{
    var innerText = document.getElementById('div1').innerHTML;

    alert( innerText );
}

OR if the text is coming from server via Ajax

$.ajax({
    url: "test.html",
    success: function(data){
        alert( data.someStringValue );
    }
});
Talha Ahmed Khan
  • 15,043
  • 10
  • 42
  • 49
  • This works if the message is static .How do I work around if its coming from server side means dynamically the message gets changed – GustyWind Aug 01 '11 at 06:48
  • Lets say if it is coming from server side, Then it will automatically be a valid variable. means that it will contain the valid string. No need to change that image. – Talha Ahmed Khan Aug 01 '11 at 06:56