javascript - Expected value not alert when click on Button? -


this question has answer here:

from code.

when click button, there alert first record.

assume have 5 records 5 buttons, each record's value = 3,4,5,6,7.

it's alert first button value = 3, button when clicked not alert , not work.

            <?php while($data = mysql_fetch_array($qr)) {  ?>             <tr>                 <td>                 <button id="btn" value="<?=$data['id']?>">ff</button>                 </td>                 <td><?=$data['schoolof']?></td>                 <td><?=$data['major']?></td>                 <td><?=$data['firstname'].' '.$data['lastname']?></td>             </tr>              <?php } ?>             <script>                 $("#btn").click(function () {                     alert($("#btn").val());                 });             </script> 

you can have 1 object same id in same page. code inserting id="btn" each button. try change code this:

        <?php while($data = mysql_fetch_array($qr)) {  ?>         <tr>             <td>             <button class="btn" value="<?=$data['id']?>">ff</button>             </td>             <td><?=$data['schoolof']?></td>             <td><?=$data['major']?></td>             <td><?=$data['firstname'].' '.$data['lastname']?></td>         </tr>          <?php } ?>         <script>             $(".btn").click(function () {                 alert($(this).val());             });         </script>