我有一个表单,其中包含一些单选按钮、一个文本字段和一个文本区域,我将它们插入到我的数据库中。现在我可以选择编辑整个内容。当我单击按钮编辑时,我再次获得表单,文本字段和文本区域中的值与我插入到数据库中的值相同。现在我不知道如何获得具有正确值的单选按钮作为检查数据库中的值。
这是我的表格:
<<<EOT
<table>
<form action="index.php?page=artikelen_bewerken_verwijderen&id={$_GET['id']}" method="post">
<tr><th><td><input type="text" size="108%" name="title" value="{$titel}"></td></tr></th>
<tr><th><td> <textarea name="description" rows="20" cols="80" >{$nieuwsbericht}</textarea></td></tr></th>
<tr><th><td><input type="radio" name="club" value="borussia-dortmund">Borussia Dortmund </td></tr></th>
<tr><th><td><input type="radio" name="club" value="ajax">Ajax</td></tr></th>
<tr><th><td><input type="radio" name="club" value="ac-milan">AC Milan</td></tr></th>
<tr><th><td><input type="radio" name="club" value="fc-bayern">Bayern Munchen</td></tr></th>
<tr><th><td><input type="radio" name="club" value="feyenoord">Feyenoord</td></tr></th>
<tr><th><td><input type="radio" name="club" value="juventus">Juventus</td></tr></th>
<tr><th><td><input type="radio" name="club" value="real-madrid">Real Madrid</td></tr></th>
<tr><th><td><input type="radio" name="club" value="fc-barcelona">Barcelona</td></tr></th>
<tr><th><td><input name="edit" type="submit" value="Edit"></td></tr></th>
</form>
</table>
EOT;
有谁知道如何像我想的那样检查单选按钮?
最佳答案
最好的方法是将整个内容写入一个 json 数组,然后让 javascript 来完成。
如果只能选择一个单选按钮:
var radio_checked = '<?php echo $row['club']; ?>';
$(document).ready(function() { // start this when site is fully loaded
if (radio_checked) { // check if variable is empty or not
$(':radio[value='+radio_checked+']').prop('checked', true);
}
});
或者如果选中了多个单选按钮(我假设您将结果转换为 PHP 中的数组):
var radio_array = <?php echo json_encode($yourArray); ?>;
$(document).ready(function() { // start this when site is fully loaded
if(!$.isArray(radio_array) || !radio_array.length) { // check if array is empty or not
for (index in radio_array) {
$(':radio[value='+radio_array[index]+']').prop('checked', true);
}
}
});
如果你不想使用 jQuery,还有一种纯 PHP 的方式,但这需要每次都编码:
<input type="radio" name="club" <?php echo ($row['club'] == 'borussia-dortmund')? 'checked' : ''; ?> value="borussia-dortmund">
<input type="radio" name="club" <?php echo ($row['club'] == 'ajax')? 'checked' : ''; ?> value="ajax">
希望对您有所帮助。
关于php - 如何通过从我的数据库中读取值来选择单选按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22837227/