PHP only returns the first value

JQUERY

When I clicked the both 2 buttons it only returns the value 1

$(document).ready(function() {
    var getvalue = $(".view_btn").val();
    $(".view_btn").click(function() {
        alert(getvalue);
    });
});

PHP

<?php foreach ($studentRankingViewGET as $studentRankingViewSHOW) {?>
<input type="button" value="<?php echo $studentRankingViewSHOW['id'];?>" class="view_btn">
<?php } ?>

This returned 2 values .i.e. 1 AND 2

Upvotes: 1

Views: 77

Answers (3)

Sarbjit Grewal
Sarbjit Grewal

Reputation: 51

This will support for dynamic content also

$(".view_btn").on("click", function() {
     alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="view_btn" value="Button 1">Button 1<button>
<button class="view_btn" value="Button 2">Button 2<button>

Upvotes: 0

Kiran Shahi
Kiran Shahi

Reputation: 7980

Since you have two buttons with same class. You can get the clicked element with this.

$(".view_btn").click(function() {
     alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="view_btn" value="Button 1">Button 1<button>
<button class="view_btn" value="Button 2">Button 2<button>

Upvotes: 0

Wils
Wils

Reputation: 1231

$('.view_btn').click(function(){
alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="button" value="123" class="view_btn"/>
   <input type="button" value="456" class="view_btn"/>

you should use $(this) as referring object.

Upvotes: 2

Related Questions