Trent Scott
Trent Scott

Reputation: 2028

How to Use PHP to Trigger a JS onClick Event

I have a signup form that has an input box hidden from view unless a link is clicked. Here's the code:

<a id="showCoupon" href="javascript:void(0);" onclick="toggleCoupon();">
     <?php _e('Have a coupon?','mysite'); ?>
</a>

If the coupon GET variable is set, I want the input box to be visible and prefilled with the supplied data. I added PHP to check for the presence of a GET variable like this:

if(isset($_GET['coupon'])) {
    $coupon = $_GET['coupon'];
}
?>

In addition, the input box has been modified to use the value of $coupon, if set. Now, I can't figure out how to trigger the JS event toggleCoupon();.

I modifying the PHP function to click the link like this:

if ( isset($_GET['coupon']) ) {
   $coupon = $_GET['coupon'];
   echo "<script>$('#showCoupon').trigger('click');</script>";
}
?>

So far, it doesn't work. What am I doing wrong?

Upvotes: 1

Views: 6012

Answers (2)

Matti Virkkunen
Matti Virkkunen

Reputation: 65166

Don't use a kludge like that. That's awful.

Instead, on the server side, don't output the piece of code (CSS class, "display: none;", whatnot) that hides the element in the first place, if the URL parameter is provided.

If the element is hidden by JavaScript, pass it a value indicating that the initial state should be visible.

Upvotes: 0

What have you tried
What have you tried

Reputation: 11148

have you tried:

<script>
$(document).ready(function(){
$('#showCoupon').trigger('click');
});

</script>

When the document loads, jQuery will trigger the click even of the element with the id of showCoupon

Upvotes: 4

Related Questions