Search code examples
phpjavascriptonclickpageload

OnClick Firing on Page Load?


My JavaScript knowledge is shallow, so I can't figure this out after some significant Googling (and searching here, of course) so I hope that this will enlighten me as to the principle of what I'm doing wrong, as well as providing a solution.

I'm putting a toggle checkbox writing a boolean to the backend database to track whether a record should be saved to a user's application 'home page'. The PHP code runs fine, and the OnClick event fires off correctly when the user clicks on the checkbox...

EXCEPT.. it also fires off every time the page is loaded. Which means when you open the page, it toggles you to the opposite of what you had previously.

Here is the code that it's firing off:

<form name="checkHomePage">
 <?php 
    echo "<input ";
    if (checkHomePage($_REQUEST['refnum']) == 1) {echo " checked='checked' ";}
    echo " onClick='<?php echo ".toggleHomePage($_REQUEST['refnum']).";?>'";
    echo " type='checkbox'>Show On My Home Page</input>";
 ?>
</form>

For the life of me, I can't figure out why the onClick is being triggered whenever the page loads. There's no JS downstream in the PHP functions, they're also returning the correct values.

Other datapoints: I'm only allowed to use minimal JavaScript on this project, such as OnClick triggers. Also, we're only using IE8 and 9 internally.

Thank you in advance.


Solution

  • The problem here is that you are sending the browser your <?php echo code. Use this instead:

    <form name="checkHomePage">
     <?php 
        echo "<input ";
        if (checkHomePage($_REQUEST['refnum']) == 1) {echo " checked='checked' ";}
        echo " onClick='toggleHomePage(".$_REQUEST['refnum'].")'";
        echo " type='checkbox'>Show On My Home Page</input>";
     ?>
    </form>