Ekumahost Ekumahost - 1 month ago 8
PHP Question

Simply JavaScript code in a loop

This script loops through a number 1-20. I discovered that the tags are repeated 20 times.

<?php for ($i = 1; $i <= 20; $i++) { ?>
<button id="btn-<?php echo $i;?>">Button<?php echo $i;?></button>
<script type="text/javascript">
$('#btn-<?php echo $i;?>').clck(function() {
alert("you clicked button <?php echo $i;?>");
});
<?php } ?>


I want to do the
$('#btn-<?php echo $i;?>').clck(function() {....
once outside the loop

Answer

The code you've written here is an anti-pattern. Use a common class on all the elements in the loop and attach a single event handler to that class. For example:

<?php for ($i = 1; $i <= 20; $i++) { ?>
    <button class="foo" data-id="btn-<?php echo $i;?>">Button<?php echo $i;?></button>
<?php } ?>
// in an external .js file far, far away
$('.foo').click(function() {
    console.log("You clicked button " + $(this).data('id'));
});

Here's a runnable code snippet. Note PHP only has to generate the HTML below. The JavaScript will then attach the click event handler to each button.

$('.foo').click(function() {
  console.log("You clicked button " + $(this).data('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="foo" data-id="1">Button 1</button>
<button class="foo" data-id="2">Button 2</button>
<button class="foo" data-id="3">Button 3</button>
<button class="foo" data-id="4">Button 4</button>