Results 1 to 3 of 3

Thread: Calling javascript function within php echo

Hybrid View

  1. #1
    Join Date
    Jul 2014

    Question Calling javascript function within php echo

    Hi all,

    I wasn't sure if this would be more appropriate here or in the client-side help forum but here goes.

    I'm a newbie when it comes to web development and I'm trying to figure out why this doesn't work...

    My code basically looks something like this:

    $value = "text";
    echo "<button onclick='myFunction($value)'>Click me</button>

    function myFunction(parameter){
    element = document.getElementById(parameter);
    element.style.color = 'blue';

    <p id="text">Change me</p>

    So, basically I want to press the button and make the text change color. It doesn't work however.

    Observations I have made:

    1. The function myFunction is called when clicking the button.
    2. It works if I change "parameter" to "text" in the function, so it looks like "element = document.getElementById("text")".

    It seems to me that there is something funky going on when I use the $value variable as parameter for the function in the echo. It just doesn't seem to get the correct string.

    Any ideas?


  2. #2
    Join Date
    Jul 2014
    I wasn't sure if this would be more appropriate here or in the client-side help forum but here goes.
    Disregard this silly sentence.

  3. #3
    Join Date
    Mar 2007
    You are right, this is a PHP problem.

    PHP Code:
    echo "<button onclick='myFunction($value)'>Click me</button> 
    should be
    PHP Code:
    echo "<button onclick=\"myFunction('{$value}');\">Click me</button>"
    Your opening and closing of quotes and escaping of quotes that need to be quotes in a string needs careful consideration.

    Where you have a ", you need a closing "
    If you have a string within that you can use ' (single quotes or \" to escape the quote

    Where you have multiple quotes, pay attention, it is easy to break your script.

    So now your code output will be
    <button onclick="myFunction('text');">Click me</button>
    --> JavaScript Frameworks like JQuery, Angular, Node <-- ... and please remember to wrap any code you have in forum tags:-
    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center

Recent Articles