2017-05-27 134 views
0

我試圖從每個價格行中獲取價值時,我側重於數量輸入,第一行工作正常,但其他行不斷警告我完全相同的價值從第一行jquery只返回第一行的值

<!DOCTYPE html> 
<html> 
<head> 
<title>Form</title> 
<script type="text/javascript" src="jquery.js"></script> 
</head> 
<body> 
<?php 
include ("dblink.php"); 

?> 

<form method="POST"> 
Customer Name: <input type="text" name="customer"><br /> 
Order Date : <input type="date" name="date"><br /> 
<br /> 

<table border='1' style='width:50%'> 
    <tr> 
     <th> Item Name </th> 
     <th> Price </th> 
     <th> Quantity </th> 
     <th> Total </th> 
    </tr> 
<?php 
    $sql = "SELECT * FROM items"; 
    $result = mysqli_query($link, $sql); 

    if(!$result){ 
     die ("SQL Error : " . mysqli_error($link)); 
    } 
    while ($row = mysqli_fetch_object($result)) 
    { 
    echo "<tr>"; 
    echo "<td class='name'>" . $row->name . "</td>"; 
    echo "<td class='itemprice' value='" . $row->price . "'>" . $row->price . "</td>"; 
?> 
    <td><input type="number" class="quantity"></td> 
    <td><div class="total"></div></td> 
<?php 
    } 
    echo "</tr>"; 
?> 
</table> 
<input type="submit" name="submit" value="Submit"> 
</form> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     $('.quantity').focus(function() { 
      var text = $('.itemprice').attr('value'); 
      alert(text); 
     }) 
    }); 
</script> 

我仍然在學習jQuery和AJAX,請大家幫忙

+1

您可能必須使用'$ .each()'進行迭代並將所有行值編譯爲一個警報。 – Rasclatt

回答

1

首先<tr>在while循環和</tr>超出while循環。所以</tr>必須在while循環中移動。

其次,如果您使用jquery類選擇器,jquery返回第一個值。所以$('.itemprice').attr('value')返回值屬性首先是.itemprice。您可以選擇.quantity的兄弟姐妹以獲得值.itemprice,該值接近此.quantity

<!DOCTYPE html> 
<html> 
<head> 
    <title>Form</title> 
    <script type="text/javascript" src="jquery.js"></script> 
</head> 
<body> 
    <?php 
    include ("dblink.php"); 
    ?> 

    <form method="POST"> 
     Customer Name: <input type="text" name="customer"><br /> 
     Order Date : <input type="date" name="date"><br /> 
     <br /> 

     <table border='1' style='width:50%'> 
      <tr> 
       <th> Item Name </th> 
       <th> Price </th> 
       <th> Quantity </th> 
       <th> Total </th> 
      </tr> 
      <?php 
      $sql = "SELECT * FROM items"; 
      $result = mysqli_query($link, $sql); 

      if(!$result){ 
      die ("SQL Error : " . mysqli_error($link)); 
     } 
     while ($row = mysqli_fetch_object($result)) 
     { 
     echo "<tr>"; 
     echo "<td class='name'>" . $row->name . "</td>"; 
     echo "<td class='itemprice' value='" . $row->price . "'>" . $row->price . "</td>"; 
     ?> 
     <td><input type="number" class="quantity"></td> 
     <td><div class="total"></div></td> 
     echo "</tr>"; 
     <?php 
    } 
    ?> 
</table> 
<input type="submit" name="submit" value="Submit"> 
</form> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     $('.quantity').focus(function() { 
      var text = $(this).siblings('.itemprice').attr('value'); 
      alert(text); 
     }) 
    }); 
</script>