javascriptphpjquerymobilejquery-on

jQuery taking the first PHP result


I'm trying to select the data that comes from the data base with jQuery, but my problem is that only the first result has a click handler bound to it.

Here is the PHP part:

<?php

$sql = "SELECT * FROM cars WHERE 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 the jQuery part:

$('#car').on('click', function(){
        var carName = $(this).attr('car-name');
        alert(carName);
    });

Let's say that i'm dynamically creating two div elements (because there are only two records in db). The jQuery recognizes only the first one. How can I make it recognize all the div elements?


Solution

  • You need to access event on class name instead ID

    <?php
    
    $sql = "SELECT * FROM cars WHERE 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);
        });