0

I am trying to place the PHP variable $e into HTML textbox id="textid" upon a button onclick. I have played around with various syntax, but I cannot seem to get it to work. What am I doing wrong?

<script type="text/javascript">
function ElementContent(id,content)
{
    document.getElementById(id).value = content;
}
</script>

<input type="text" name="" value ="" id="textid" ;"/>

<?php
$e = "test";
echo '<button value="" class="button" onclick="ElementContent(\'textid\',\'$e\')" />';
?>
2
  • 1
    A button is not self-closing. It should be <button>label</button>. Commented Jan 15, 2014 at 13:45
  • Not quite true, every tag can be self closed in XHTML Commented Jan 15, 2014 at 13:48

2 Answers 2

4
echo '<button value="" class="button" onclick="ElementContent(\'textid\',\''.$e.'\')" />Button Name</button>';

You have to concat the string, as php doesn't automatically recognise dollars+some name as a variable in single quote strings.

Sign up to request clarification or add additional context in comments.

3 Comments

fix this part $e\.''
<button> is not self-closing.
Also, notice <input type="text" name="" value ="" id="textid" ;"/> (superfluous ;"). Might cause issues in certain browsers.
3

PHP variables will only be interpreted in strings constructed with double-quotes ("). Update your code as follows:

<button value="" class="button" onclick="ElementContent('textid', '<?php echo $e ?>')" />

As you can see, there's no need to output the whole button markup in PHP. Thus, your final code should be:

<script type="text/javascript">
function ElementContent(id,content) { document.getElementById(id).value = content; }
</script>

<input type="text" name="" value ="" id="textid" />

<?php $e = "test"; ?>
<button value="" class="button" onclick="ElementContent('textid', '<?php echo $e ?>')">Button</button>

I also took the time to fix a few issues with your markup, too.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.