skip to Main Content
<?php
for($i=0;$i<5;$i++){
?>
<button id="text<?php echo $i; ?>">hello </button>
<script>
var i=<?php echo $i; ?>;
  $(document).ready(function(){
     $("#text"+i).click(function(){
             alert("hello");
   })

})

</script>
<?php } ?>

If I have a varying id like this and I want to call it in jQuery using this code its give me no result. Where is the problem? How can I call an element like this button?

2

Answers


  1. Would be better to move the script out of the loop, get the buttons all at once and then bind the click event:

    // Create all buttons, with class "text-button"
    <?php for($i=0;$i<5;$i++): ?>
      <button class="text-button" id="text<?php echo $i; ?>">hello </button>
    <?php endif; ?>
    
    <script>
    // On document ready
    $(document).ready(function() {
      // Find all buttons with class "text-button"
      $(".text-button").click(function(e) {
        alert("hello");
    
        // Log the clicked button
        console.log(e.currentTarget);
        console.log(e.currentTarget.id);
      })
    })
    </script>
    
    Login or Signup to reply.
  2. I am satisfied with @Emre’s answer. And also remove $(doucment).ready() will solve your problem. Like this.

    <?php
    for($i=0;$i<5;$i++){
    ?>
    <button id="text<?php echo $i; ?>">hello </button>
    <script>
    var i=<?php echo $i; ?>;
         $("#text"+i).click(function(){
                 alert("hello");
       });
    </script>
    <?php } ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search