tags:

views:

58

answers:

2

I'm using the following code in php:

PHP:

 $suggested_sentence[0] = "Hello, how are you?";
  echo $suggested_sentence[0] . ' <input type="image" src="button.png" 
  onclick = update_textarea('. $textareacount.','. "'".$suggested_sentence[0]."')/>";

Javascript function:

function update_textarea(count, new_sentence) {
    document.getElementById('sentence' + count).value = new_sentence;
}

But when i press the button i get the error "unterminated string literal but if i change the value of $suggested_sentence[0] = "Hello" it works fine.

What should i do then?

A: 

HTML encode $suggested_sentence[0] as it may contain characters that break the javascript literal (such as ' so make sure you set quote_style to ENT_QUOTES for this).

Darin Dimitrov
This is a good suggestion, although not the culprit in this case.
TNi
+1  A: 

Check the file after PHP has executed to ensure that your button looks like this...

<input type="image" src="button.png" onclick="update_textarea(1, 'Hello, how are you?');"/>

Note that the onclick event is surrounded with double-quotes.

You can adjust your example like this:

 $suggested_sentence[0] = "Hello, how are you?";
  echo $suggested_sentence[0] . ' <input type="image" src="button.png" 
  onclick="update_textarea('. $textareacount.', '. "'" . $suggested_sentence[0]."'" . ')"/>';
Sohnee
Thanks alot it is working now.You are the best. You have saved my time.
fawad
@fawad, glad I could help. Feel free to click on that tick next to the answer if it solved your problem. Cheers :)
Sohnee