我正在使用 php,但经验较少。我在表格中显示数据,表格的每一行开头都有一个单选按钮。我想检索与我检查的单选按钮对应的行中存在的所有数据。 这是我到目前为止所做的事情:
<form name="test" method="POST">
<table>
<tr>
<th></th>
<th>book_id</th>
<th>card no</th>
<th>fname</th>
<th>lname</th>
</tr>
<?php
$conn = mysql_connect("localhost", "root", "");
if ($conn) {
mysql_select_db("library");
} else {
echo 'no such database';
}
$query_test = "select book_id2,a.card_no,fname,lname from book_loans a, borrower b where a.card_no = b.card_no ";
$result = mysql_query($query_test);
if ($result === FALSE) {
mysql_error();
} else {
while ($rows = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td><input type='radio' name='test'></td>";
echo "<td>" .$rows['book_id2']. "</td>";
echo "<td>" .$rows['card_no']. "</td>";
echo "<td>" .$rows['fname']. "</td>";
echo "<td>" .$rows['lname']. "</td>";
echo "</tr>";
}
}
?>
<input type="submit" name="test_val" value="submit"/>
</table>
</form>
这里我想在点击提交按钮时打印数据,即 book_id、card_no、fname、lname:
<?php
if($_POST)
{
if(isset($_POST['test_val']))
{
// TO PRINT THE DATA CORRESPONDING TO THE RADIO BUTTON
}
}
?>
最佳答案
在每个 <td>
中添加隐藏的输入字段行。例如:
echo "<td>".$rows['book_id2']."</td><input type='hidden' name ='book_id2' value='".$rows['book_id2']."' />";
我试过编写 JavaScript,但这在 JQuery 中要容易得多。在结束前添加这些脚本 </body>
标签。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var toggleInput = function(){
$('input[type=hidden]').prop('disabled', true);
var selection = $('input:checked').eq(0);
selection.parent().parent().find('input[type=hidden]').each(function(){
$(this).prop('disabled',false);
});
}
$(form).on('submit',toggleInput);
</script>
JQuery在像这样操作 DOM 时经常使用。它减少了很多在 JavaScript 中可以看到的重复。尽管如果只用 JavaScript 做某事更容易,那就去做吧!
在提交表单时,我们将禁用所有隐藏元素。然后我们找到激活的单选框,激活单选框对应的隐藏元素。
这是一种解决方案,可能需要进行调整。 JavaScript 和 JQuery 是解决这个问题的好 helper 。
关于javascript - PHP - 检索与单选按钮对应的所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31536884/