I have data in a PHP array I want to turn into buttons.
For simplicity, these buttons will console.log() their data on click.
Right now I'm using inline event handlers to do this.
How do I approach this problem using data attributes and no inline event handlers? I know how to create data attributes, but I don't know how to log the data and bind event listeners to the buttons.
<script>
function logData(lat, long) {
console.log(lat);
console.log(long);
}
</script>
<?php
$coordinates = array(
first => array(
"lat" => "64",
"long" => "89"
),
second => array(
"lat" => "23",
"long" => "11"
),
third => array(
"lat" => "35",
"long" => "76"
)
);
// Create buttons with inline event handlers
foreach($coordinates as $point) {
echo "<button onclick='logData(".$point["lat"].", ".$point["long"].")'>Button</button>";
}
echo "<br><br>";
// Create buttons with data attributes. How do you log the data without inline event handlers?
foreach($coordinates as $point) {
echo "<button data-lat=".$point["lat"]." data-long=".$point["long"].">Button</button>";
}
?>