1

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?

2
  • Do you just want to be able to execute some JavaScript when the user clicks the link? Commented Mar 23, 2013 at 18:37
  • No, I want to prefill a text field with a get variable which is hidden from default view unless a link is clicked. Commented Mar 23, 2013 at 18:37

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

8 Comments

That worked, thanks! So, I was missing the $(document).ready? Thought I didn't need it since it was being executed by PHP, not on page load necessarily.
The code is not being executed by PHP. PHP is a server side language. Your simply telling the page to load that script if a certain circumstance is met. But the actual running of that script is not going to happen until the page loads, in this case when the DOM is ready
Got it, that makes sense! I'll mark your answer as soon as it lets me.
Downvoted for kludge. The correct way is not to simulate a click, the correct way is to not hide the element in the first place.
@MattiVirkkunen The question was "how can I trigger event x" - I showed him how he could do so.
|
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.