Reputation: 1413
<?php
include "connection.php";
$query="select n_id,title,news from news ";
$queryr=$con->query($query);
while($row=$queryr->fetch_assoc())
{
?>
<?php echo $row['title'];?>
<a href="#" id="readmore">... Read More</a>
<input type="hidden" id="idd" name="idd" value="<?php echo $row['n_id'];?>" >
<?php } ?>
Here is my php code that retrieves values from database. I want to alert the id of each row . Below is my script :
<script>
$(document).ready(function(){
$("#readmore").click(function(){
var id=$("#idd").val();
alert(id);
});
});
</script>
At present I am only getting the id of first value fetched from database. How it is possible with the rest of the values? Thanks in advance.
Upvotes: 1
Views: 106
Reputation: 3309
Use jquery each function like this
$('.readmore').each(function(e) {
e.preventDefault();
var id = $(this).next('.idd').val();
alert(id);
}
Upvotes: -1
Reputation: 31749
Use class
selector instead of id
. id
supposed to be unique. You can not have same id
for multiple elements. In this case class
will work perfectly.
<a href="#" class="readmore">... Read More</a>
<input type="hidden" class="idd" name="idd" value="<?php echo $row['n_id'];?>" >
$(".readmore").click(function(e){
e.preventDefault(); // Only if you dont want it to reload
var id=$(this).next('.idd').val();
alert(id);
});
Upvotes: 1
Reputation: 178094
ID needs to be unique:
Change to class="readmore" and input's class="idd" and use
$(".readmore").click(function(e){
e.preventDefault()
var id=$(this).next(".idd").val();
alert(id);
});
Alternatively do this:
<?php echo $row['title'];?>
<a href="#" class="readmore" data-id="<?php echo $row['n_id'];?>">... Read More</a>
<?php } ?>
using
$(".readmore").click(function(e){
e.preventDefault()
var id=$(this).data("id");
alert(id);
});
Upvotes: 1