I have a code in PHP that prints HTML elements based on the information we got in the database, so if we have for example 8 products the code will print 8 divs with the following elements inside
- h1 the id of this element will be the same as the product in the database
- input for client name
- buy button that send the ID of the H1 to the database
here is some code i made
<?php
while($row=$consulta->fetch())
{
?> <img src="<?php echo $row["Imagen"];?>"style="width:12rem;height:12rem;" alt="Scotter" >
<br>
<div>
<h4 id="<?php echo $row["ID_Scooter"]; ?>"> <?php echo $row["ID_Scooter"]; ?> </h4>
<br>
<?php
echo $row["Nombre"];
?>
<br>
<?php
echo $row["Descripcion"];
?>
<br>
<?php
?>
<button onclick="abrir()">Alquilar</button>
<br>
</div>
<?php
}
?>
JavaScript
function abrir(){
var dialog = document.getElementById('favDialog');
dialog.show();
var id=document.getElementById("heres is where im supposed to get the id of the id i clicked");
alert("div id is="+id);
}
php assing ID for example (3,4,5,6,7) but when i click the button inside the div with id=5 it prints the id=3 no matter which button i click
My Answer:
To get the ID of the element that was clicked, you can pass the ID as a parameter to the `abrir()` function. Here's how you can modify your PHP code to achieve this:
php
while($row=$consulta->fetch())
{
?>
" style="width:12rem;height:12rem;" alt="Scotter">
">
}
And in your JavaScript function, you can receive the ID parameter and use it to get the correct ID of the element that was clicked:
javascript
function abrir(id){
var dialog = document.getElementById('favDialog');
dialog.show();
alert("div id is=" + id);
}
Now, when you click the "Alquilar" button inside a div, it will pass the correct ID to the `abrir()` function and alert the correct ID of the element that was clicked.
Rate this post
5 of 5 based on 3841 votesComments