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>
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
id's should be unique, try using a class instead.
Most browsers when selecting the ID in javascript respect the standard and respond you with only the first element.
Try removing the ID
<div class="col-xs-3 text-right">
<button class="btn btn-xs btn-warning btn-icon"><i class="fa fa-plus"></i></button>
</div>
and then:
$(".btn").on("click",function() {
alert("hey");
});