0
<?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 2

3

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>
Sign up to request clarification or add additional context in comments.

Comments

0

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 } ?>

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.