Reputation: 237
for($i=0;$i<5;i++)
{
<h2><a href="" class="question_title"><?php echo $value['asked_title'];?> </a></h2>
<input type="hidden" name="question_id" value="<?php echo $i; ?>" id="question_id" class="question_id" >
}
Jquery :
$('.question_title').click(function () {
var value = $('#question_id').val();
alert(value);
});
Friends in this code question_id will be carrying different values for the looping . Here I have writtern code to get the value according to the LOOPING on click of ahref class I would like to fetch the value of hidden value for example in the first iteration title is cow on click ahref it should alert 0 (question_id value). on click on 2nd title cat it should get alert 1 like on clicking 5 different title it should display 0-4 respectively but now onclick on different title it alerts only 0 not the other values . could any one suggest me how to achieve it .
Upvotes: 1
Views: 108
Reputation: 614
As 'id' is unique value, it will get only the first element.
Try this:
for($i=0;$i<5;i++)
{
<h2><a href="" class="question_title" id="<?php echo $i; ?>"><?php echo $value['asked_title'];?> </a></h2>
}
Jquery :
$('.question_title').click(function()
{
alert(event.target.id);
});
Upvotes: 0
Reputation: 1484
You are having the same id question_id
in all five hidden fields.
you can have it like this..
for($i=0;$i<5;i++)
{
echo '<h2><a href="" class="question_title" data-value="'.$i.'">'.$value['asked_title'].'</a></h2>';
}
jquery
$('.question_title').click(function()
{
var value = $(this).data('value');
alert(value);
});
Upvotes: 0
Reputation: 2408
For
<?php
for($i=0;$i<5;i++)
{
?>
<h2><a href="#" class="question_title" data-tell="<?php echo $i; ?>"><?php echo $value['asked_title'];?> </a></h2>
<input type="hidden" name="question_id" value="<?php echo $i; ?>" id="question_id" class="question_id" >
<?php } ?>
And in script use
$('.question_title').click(function() {
alert($(this).attr("data-tell"));
});
Upvotes: 0
Reputation: 20750
Get the parent h2
and then next .question_id
like following.
$('.question_title').click(function() {
var value = $(this).parent().next('.question_id').val();
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2><a href="" class="question_title">Title 0</a></h2>
<input type="hidden" name="question_id" value="0" id="question_id" class="question_id">
<h2><a href="" class="question_title">Title 1</a></h2>
<input type="hidden" name="question_id" value="1" id="question_id" class="question_id">
BTW you are using same id question_id
for multiple elements.
Upvotes: 1