JavaScript 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?

Answer:1

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);
    });
Answer:2

Instead of id (#car) use class(.car) for the div

PHP

echo '<div class="car" car-name="'.$carName.'">'.$carName.'</div>';

JQUERY

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

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

Because the click handler being attached by browser is faster than your php rendering.If you will attach a click handler on document then it will work always.

Hope this helps

Thanks

Answer:4

You should add class car:

<?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 'ολα τα αυτοκινιτακια ειναι νοικιασμενα';
}

?>

Jquery

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

Hope this helps you :)

Answer:5

Per the MDN documentation for attribute id:

The id global attribute defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).1

So when creating the div elements, give them unique values for the id attribute. In order to add the click handler to all elements for the car elements, add a class attribute (e.g. class="car") to the <div> elements:

echo '<div id="car_'.$carName.'" car-name="'.$carName.'" class="car">'.$carName.'</div>';

Then use the class selector (i.e. .car) in the click-handler:

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

See this demonstrated below (with PHP code removed, since this sandbox doesn't support it):

$('.car').on('click', function(){
        var carName = $(this).attr('car-name');
        alert(carName);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="car_MDX" car-name="MDX" class="car">MDX</div>
<div id="car_m3" car-name="m3" class="car">m3</div>
<div id="car_z3" car-name="z3" class="car">z3</div>
Answer:6

We are running a quick javascript function to fill out and save a form to quickly move forward in a workflow (for testing purposes). It's running fine in all browsers except for Firefox - and only on ...

We are running a quick javascript function to fill out and save a form to quickly move forward in a workflow (for testing purposes). It's running fine in all browsers except for Firefox - and only on ...

I want to use jQuery's multiple selectors and set on() on them and then using "$(this)" implement something I need. This should look like this: $(".one, .two, .three").on("someEvent", function () { ...

I want to use jQuery's multiple selectors and set on() on them and then using "$(this)" implement something I need. This should look like this: $(".one, .two, .three").on("someEvent", function () { ...

  1. using this with arrow functions
  2. using this with jquery
  3. using this with a constructor
  4. using this with class jquery
  5. using this with javascript
  6. using this with typescript
  7. using this in java
  8. using this in a sentence
  9. using this in constructor c++
  10. using this in c#
  11. using this to start a sentence
  12. using this in node.js
  13. using this in html
  14. using this in parameter c#
  15. using this in past tense
  16. using this in javascript onclick
  17. using this in lambda java
  18. using this in javascript class
  19. using this in python
  20. using $ this in ajax jquery

when i am trying to write code for login with linkedin i am getting error like the below. Uncaught Error: You must specify a valid JavaScript API Domain as part of this key's configuration. Below is ...

when i am trying to write code for login with linkedin i am getting error like the below. Uncaught Error: You must specify a valid JavaScript API Domain as part of this key's configuration. Below is ...

In an article on browser plugin development, they use this code: window.browser = (function () { return window.msBrowser || window.browser || window.chrome; })(); Why would they use an ...

In an article on browser plugin development, they use this code: window.browser = (function () { return window.msBrowser || window.browser || window.chrome; })(); Why would they use an ...