我可以为复选框的已选中和未选中状态分配值吗? [英] Can I assign values to a checkbox for checked and unchecked states?
问题描述
我有一个复选框,希望将值分配给选中状态和未选中状态。
值保存在MySQL数据库中。这是我的PHP来检索值。
I have a single checkbox in a form which I want to assign values to for both checked and unchecked states. The values are saved in a MySQL database. This is my php to retrieve the values.
<?php
// Value = 10.00
// This should be the checked value (initial state)
function getDel1()
{
global $con;
$get_del1 = "select * from delivery";
$run_del1 = mysqli_query($con, $get_del1);
while($row_del1=mysqli_fetch_array($run_del1)){
$leeds = $row_del1['delivery_leeds'];
echo "$leeds";
}
}
?>
<?php
// Value = 20.00
// This should be the unchecked value (user interaction)
function getDel2()
{
global $con;
$get_del2 = "select * from delivery";
$run_del2 = mysqli_query($con, $get_del2);
while($row_del2=mysqli_fetch_array($run_del2)){
$leeds = $row_del2['delivery_other'];
echo "$other";
}
}
?>
我可以通过在与表单复选框相邻的div中调用任一函数来独立显示值我不知道如何将这些值分配给表单复选框,然后根据用户交互自动更新div。有建议吗?
I can display the values independently by calling either function in a div which is adjacent to the form checkbox but I don't know how to assign those values to the form checkbox and then automatically update the div depending on the user interaction. Any suggestions?
推荐答案
三元运算符可以同时处理分配的值和未分配的默认值。
A ternary operator can take care of both assigned values and unassigned default values.
示例:
$checkbox = isset($_POST['checkbox']) ? $_POST['checkbox'] : "Default value if unchecked";
这等效于执行:(也可以使用)。
This is equivalent to doing: (which you can also use).
if (isset($_POST['checkbox'])){
$checkbox=$_POST['checkbox'];
// do something, as in run a function
}
else{
$checkbox="Default value if unchecked";
// do something else, as in run a different function
}
您也可以删除默认文本并在三元数中执行
使其为空。
You can also remove the default text and do ""
in the ternary to leave it empty.
参考:
- http://php.net/manual/en/language.operators.comparison.php
脚注:
确保复选框具有名称属性。
Make sure the checkbox holds the name attribute.
即 name = checkbox
作为示例。
并且您的表单具有POST方法。相应地,使用适当的方法。
and your form has a POST method. Use the appropriate method accordingly.
- 因此,在您的情况下,以及从留在此处的代码的注释中可以看到,更改
数组中的复选框
来交付
。
- So in your case and as seen in comments from code you left there, change
checkbox
in the arrays todeliver
.
您的复选框值也可以使用以下示例作为一个示例:
Your checkbox value can also use the following, as a ternary example:
<input type="checkbox" name="deliver" value="<?php echo isset($_POST['deliver']) ? $_POST['deliver'] : "Default value if unchecked"; ?>" />
这篇关于我可以为复选框的已选中和未选中状态分配值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!