dcsimg
www.webdeveloper.com
Results 1 to 3 of 3

Thread: Calling javascript function within php echo

  1. #1
    Join Date
    Jul 2014
    Posts
    2

    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:


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

    <script>
    function myFunction(parameter){
    element = document.getElementById(parameter);
    element.style.color = 'blue';
    }
    </script>

    <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?

    Thanks!

  2. #2
    Join Date
    Jul 2014
    Posts
    2
    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
    Location
    localhost
    Posts
    2,887
    You are right, this is a PHP problem.

    This
    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
    Code:
    <button onclick="myFunction('text');">Click me</button>
    STOP using $ prefix on JavaScript variable names...
    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