Forum

Thread tagged as: Question, Members

How do I include inline javascript in a php echo?

I'm working with the members app, echoing certain options for a person that's logged in. In this instance, I have a set of buttons that toggle one of two divs with a hide/show javascript function.

How do I include the toggle function in this? Right now it causes a php error.

echo'<a class="button" onclick="toggle('InqForm');">Research Inquiry</a><div class="togglehidden" id="surnameInqForm"></div>';

Or is there a better way to structure it?

Gary Iverson

Gary Iverson 0 points

  • 7 years ago
Drew McLellan

Drew McLellan 2638 points
Perch Support

To do it that way, you need to escape the single quotes with backslashes so that they don't end the string:

echo'<a class="button" onclick="toggle(\'InqForm\');">Research Inquiry</a><div class="toggle hidden" id="surnameInqForm"></div>';

Another way is to break out of PHP and just write it to the page:

?>
<a class="button" onclick="toggle('InqForm');">Research Inquiry</a><div class="toggle hidden" id="surnameInqForm"></div>
<?php

And if you're really up for rethinking things, writing inline JavaScript is considered a bit old hat. You might want to read up on unobtrusive JavaScript. Here's a good primer: https://blog.teamtreehouse.com/unobtrusive-javascript-important

I'll look into that, thank you. I'm so into rethinking it that I might not really need JavaScript at all for this...I could just show both forms which saves a click or tap.