Amirh_ba Amirh_ba - 2 months ago 4
PHP Question

jquery just works for the latest button not all button

My PHP HTML code is this :

<?php

foreach($questions as $question){

echo"
<div id='postShare'>

<div class='col-md-10 col-md-offset-1' id='listPost'>
<div class='list-group'>
<li class='list-group-item text-center '><span class='pull-left' id='question_author'>".$question->author."</span>
&nbsp;
<span class='pull-right' id='question_time'><p>".time_ago($question->time)."</p></span>
<hr>
<span class='pull-right' style='color:red;font-size:11px;'>سوال</span><br><center><h4 id='question_title'>" .$question->title. "</h4></center><hr>

<span class='pull-right' style='color:blue;font-size:11px;'>توضیحات</span><br><h5 id='question_desc'>".$question->description."</h5><hr>
<span class='pull-right' style='color:GoldenRod;font-size:11px;'>کد برنامه</span><br><pre id='question_code'>".$question->code."</pre><hr>

<button class='btn btn-primary' id='send_answer'>پاسخگویی به این سوال</button>
</li>
</div>
</div>

</div>";

}

?>


and my Jquery file is this :

$(function(){

$("#send_answer").click(function(e){

alert("cliked");

e.preventDefault();
});
});


PHP code just fetch and show the database data with a button.
i want when i click at that button it shows an alert . its work for the latest data that fetch and do not work for all
help me thanks

Answer

You need to create button with the same class. Creating with a same id will result in only one to be operated on.

PHP

 <?php 
     foreach($questions as $question) {
         echo "
            <div id='postShare'>
                <div class='col-md-10 col-md-offset-1' id='listPost'>
                     <div class='list-group'>    
                        <li class='list-group-item text-center '>
                            <span class='pull-left' id='question_author'>".$question->author."</span>&nbsp;
                            <span class='pull-right' id='question_time'><p>".time_ago($question->time)."</p></span><hr>
                            <span class='pull-right' style='color:red;font-size:11px;'>سوال</span><br><center><h4 id='question_title'>"  .$question->title. "</h4></center><hr>
                            <span class='pull-right' style='color:blue;font-size:11px;'>توضیحات</span><br><h5 id='question_desc'>".$question->description."</h5><hr>            
                            <span class='pull-right' style='color:GoldenRod;font-size:11px;'>کد برنامه</span><br><pre id='question_code'>".$question->code."</pre><hr>
                            <button class='btn btn-primary send_answer'>پاسخگویی به این سوال</button>
                        </li>
                    </div>
                </div>
            </div>";
     }
 ?>

jQuery

$(function() {
    $(".send_answer").click(function(e) {
        alert("cliked");
        e.preventDefault();
    });
});