Forum Moderators: open

Message Too Old, No Replies

Syntax with quotes, onclick and innerHTML call problem

text to change onclick to text field

         

Philiboy

2:03 pm on Mar 10, 2009 (gmt 0)

10+ Year Member



Hi I am having problems with some syntax. Can anyone help?
The output for the non-working part contains...

<button> "/> text to change

... instead of ....

<button> text to change

(plus it does not function)....My comments in the code explain more.

<p>--------------code below works fine--------</p>
<input type="button" value="Click" onclick="document.getElementById('b').innerHTML='newtext'"/>
<span id="b">text</span>
<p>--------------but can't get code below to work. Want to get 'text to change' to change to an input field--------</p>

<?php

$newtext = '<input type="text" name="name1" size="30" value="somevalue"/>';
?>

<input type="button" value="Edit" name="name2" onclick="document.getElementById('a').innerHTML=<?php print $newtext; ?>"/>
<span id="a">text to change</span>
<p>-----------------------</p>
Thanks, in anticipation of your help.

penders

2:31 pm on Mar 10, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



After PHP has parsed your file, the resulting JavaScript becomes...
onclick="document.getElementById('a').innerHTML=<input type="text" name="name1" size="30" value="somevalue"/>"

As you can probably see, you are missing string delimiters '...' around your newtext and there is now a mismatch of double quotes with the string you are trying to assign to innerHTML and the onclick attribute itself (these need to be escaped).

So (also swapping around the double and single quotes) ...

<?php  
$newtext = "<input type=\\'text\\' name=\\'name1\\' size=\\'30\\' value=\\'somevalue\\' \/>";
?>

<input type="button" value="Edit" name="name2" onclick="document.getElementById('a').innerHTML='<?php print $newtext; ?>'"/>

However, the better solution would be to not use inline JavaScript and keep it in an external file. Then you wouldn't have to mess around escaping everything.

<edit>Corrected the escapes! *sigh*</edit>

penders

3:43 pm on Mar 10, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Note... there are 2 lots of escaping going on here with using PHP and JavaScript. First, the double backslash (\\) in the PHP results in just a single backslash (followed by a single quote... \') in the PHP - which gets output to the JavaScript. And this then becomes just a single quote in the resulting JavaScript that is executed. The single quotes need to be escaped in the JavaScript because we're now using single quotes to delimit our JavaScript string.

Philiboy

7:31 pm on Mar 10, 2009 (gmt 0)

10+ Year Member



This is great, penders. Mixing technologies such as PHP and Javascript can be a challenge, which you have risen to. Thanks.