当我专注于数量输入时,我试图从每个价格行获取值,第一行工作正常,但其他行不断提醒我第一行的完全相同的值
<!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,请帮忙
最佳答案
第一<tr>
处于 while 循环中且 </tr>
已退出 while 循环。所以</tr>
必须在 while 循环中移动。
其次,如果使用jquery的类选择器,jquery返回第一个值。所以$('.itemprice').attr('value')
首先从.itemprice
返回值属性。您可以选择 .quantity
的 sibling 获取 .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>
关于php - jquery只返回第一行的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44213609/