<html>
<head>
<link rel="stylesheet" href="js/jquery-ui-themes-1.11.1/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.11.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$(".buttonsPromptConfirmDeleteDepartment").click(function(){
var departmentID = $('input#departmentID').val();
alert(departmentID);
});
});
</script>
</head>
<body>
<?php
//db connection
$query = "SELECT *
FROM department
ORDER BY dept_ID ASC";
$result = mysqli_query($dbc, $query);
$total_department = mysqli_num_rows($result);
if($total_department > 0)
{
?>
<table width="600" border="1" cellpadding="0" cellspacing="0" style="border-collapse:collapse">
<tr>
<td width="80" align="center">ID</td>
<td width="300" align="center">Department</td>
<td width="220" align="center">Action</td>
</tr>
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td align="center"><?php echo $row['dept_ID']; ?></td>
<td align="center"><?php echo $row['dept_name']; ?></td>
<td>
<button class="buttonsPromptConfirmDeleteDepartment">Delete</button>
<input type="hidden" id="departmentID" value="<?php echo $row['dept_ID']; ?>" />
</td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
部门表
DEPT_ID DEPT_NAME
1个帐户
2财经
3个营销
假设我的部门表只有3条记录
我的要求如下:
- 单击第一个删除按钮,显示部门ID = 1
- 单击第二个删除按钮,显示部门ID = 2
- 单击第3个删除按钮,显示部门ID = 3
但是从我的代码来看,我无法满足我的要求。
无论我点击什么按钮,我得到的部门ID输出都是1。
有人可以帮助我吗?
答案 0 :(得分:1)
无需使用隐藏输入,您只需使用button
标记:
<?php while($row = mysqli_fetch_array($result)) { ?>
<tr>
<td align="center"><?php echo $row['dept_ID']; ?></td>
<td align="center"><?php echo $row['dept_name']; ?></td>
<td>
<button type="submit" name="departmentID" class="buttonsPromptConfirmDeleteDepartment" value="<?php echo $row['dept_ID']; ?>">Delete</button>
</td>
</tr>
<?php } ?>
当然,在执行表单处理的PHP脚本中,像通常那样访问POST索引:
$id = $_POST['departmentID'];
// some processes next to it
注意:不要忘记<form>
标记。
附加说明:不要忘记使用预备语句:
$sql = 'DELETE FROM department WHERE dept_ID = ?';
$stmt = $dbc->prepare($sql);
$stmt->bind_param('i', $id);
$stmt->execute();
// some idea, use error checking when necessary
// $dbc->error
答案 1 :(得分:0)
更改
ID = “DepartmentID的”
到
class =“departmentID”和
更改
<script>
$(document).ready(function(){
$(".buttonsPromptConfirmDeleteDepartment").click(function(){
var departmentID = $('input#departmentID').val();
alert(departmentID);
});
});
到
<script>
$(document).ready(function(){
$(".buttonsPromptConfirmDeleteDepartment").click(function(){
var departmentID = $(this).next('input.departmentID').val();
alert(departmentID);
});
});
答案 2 :(得分:0)
首先在while循环中使用dept_id并且你为所有dept使用相同的id .. 另一件事你可以使用jquery按钮点击dept_id ..像这样
$('.buttonsPromptConfirmDeleteDepartment').click(function(){
dept_id = $(this).next('input').val();
})