Is it possible to add event listener using PHP?

12,406

Solution 1

Simply add a class to the radio buttons, then using JavaScript/JQuery, you could add event listeners to the inputs as needed.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="myjsfile.js"></script>
<input type="radio" class="clickyradio" />
<input type="radio" class="clickyradio" />
<input type="radio" class="clickyradio" />

now in the file myjsfile.js

$(document).ready(function() {
   $('.clickyradio').click(function() {
      // whatever you want to happen when it gets clicked
      // "this" keyword will refer to the input element that got clicked

   });
});

if you need the click to communicate something to the server, put an ajax call within the click event handler.

Solution 2

The closest thing you'll get to a php event listener is calling some specific php functionality via ajax, after a javascript event has fired. that request is technically attached to the chain of events (callbacks) from the client side.

but php doesn't do that because its not client side.

Share:
12,406
Ani
Author by

Ani

I'm a software engineer who enjoys challenges (read: building new systems and fixing up those bugging bugs) I love to develop new games &amp; ideas (computer, web, mobile, console), especially in the use of games as a learning aid. Specialties: Games development (esp. with HTML5/Javascript for smartphones &amp; tablets), Software Design &amp; Development, Building &amp; managing new teams, Financial Modeling &amp; Analysis SOreadytohelp

Updated on June 13, 2022

Comments

  • Ani
    Ani almost 2 years

    I'm creating a survey form using Smarty templates in which I want to attach an event with radio buttons of a particular question such that it pops-up a message when any one of them is clicked.

    So I want to add a click/change event listener on them but don't know how to do it using PHP. As I do not know the radio button id in advance (they are generated on the fly), I'm not sure if I can use JavaScript here. Any solutions/suggestions?

    Google search returns all sort of answers for adding event listeners for Android and JavaScript which are of no use!

  • Ani
    Ani almost 12 years
    I've worked with JS, so that's not a issue. I wasn't aware that I can create JS within PHP as suggested by Jack in comments above, so now searching how to do that. I think it will solve my prob. If you have a code to illustrate that, it would be very helpful. Thanks!
  • Ani
    Ani almost 12 years
    Thnx for the code! I had the issue since I was using an existing system to build upon... did some hunting and ugly hacks to incorporate the idea... and there it was!!! Working as needed :)