javascript - jQuery taking the first PHP result -
i'm trying select data comes data base jquery, problem first result has click handler bound it.
here php part:
<?php $sql = "select * cars rented = '0'"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { $carname = $row['name']; echo '<div id="car" car-name="'.$carname.'">'.$carname.'</div>'; } }else{ echo 'ολα τα αυτοκινιτακια ειναι νοικιασμενα'; } ?>
and jquery part:
$('#car').on('click', function(){ var carname = $(this).attr('car-name'); alert(carname); });
let's i'm dynamically creating 2 div elements (because there 2 records in db). jquery recognizes first one. how can make recognize div elements?
you need access event on class name instead id
<?php $sql = "select * cars rented = '0'"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { $carname = $row['name']; echo '<div class="car" car-name="'.$carname.'">'.$carname.'</div>'; } }else{ echo 'ολα τα αυτοκινιτακια ειναι νοικιασμενα'; } ?>
js
$('.car').on('click', function(){ var carname = $(this).attr('data-car-name'); alert(carname); });
Comments
Post a Comment