adetiwa adetiwa - 2 months ago 10
Javascript Question

When I loop through a MySQL array, JavaScript works on the first echoed data

I am having trouble getting a desired result on my code. When I loop through an array of data, JavaScript works only on the first echoed data.

Code Snippet:

<?php

$ids = array();


array_push($ids, getRandom($id));
array_push($ids, getRandom($id));
array_push($ids, getRandom($id));

$ids = array_unique($ids);
if (count($ids) > 0) {
foreach($ids as $value => $val) {

//data saved in variables


<li>
<div class="row">
<div class="col-xs-3">
<div class="avatar">
<!--avartar -->
</div>
</div>
<div class="col-xs-6">
<!-- data -->
</div>
<div class="col-xs-3 text-right">
<button id = "button1" class="btn btn-xs btn-warning btn-icon"><i class="fa fa-plus"></i></button>
</div>
</div>
</li>
<?php
}
}
?>


JavaScript:

<script>
$("#button1").on("click",function() {
alert("hey");
});
</script>

Answer

Try changing the JavaScript function to work for any button click:

$("button").on("click",function() {
    alert("hey");
});

And it's also worth noting you shouldn't use the same ID for more than one element:

<button id = "button_<?= $val ?>" class="btn btn-xs btn-warning btn-icon"><i class="fa  fa-plus"></i></button>

This will create a unique ID for each button element