Search code examples
phpdom-eventssmarty

Is it possible to add event listener using PHP?


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!


Solution

  • 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.