我使用下面的选择列表功能制作一个内部有5个值的选择列表。当我选择它们时,值2-5工作正常,当我选择它们时,它们会在页面上打印出它们的值,但无论如何,值1都不会打印出来。我无法弄清楚我做错了什么或如何解决它。请看一下我的代码:
index.php
function limit($count,$location) {
echo "<form method = 'POST' action = '$location'>";
echo "<select name = 'value' onchange='this.form.submit()'>";
while ($tempCount < $count) {
$tempCount++;
echo "<option value='$tempCount'>$tempCount</option>";
}
echo "</select>";
echo "</form>";
}
limit(5,"index.php")
$value = $_POST['value'];
echo $value;
答案 0 :(得分:1)
向< select >
添加一个第一个选项,并检查是否存在$_POST['value']
。接下来是您的代码,其中两个更改都由注释箭头指向(//&lt; =====):
<?php
function limit($count,$location) {
echo "<form method = 'POST' action = '$location'>";
echo "<select name = 'value' onchange='this.form.submit()'>" .
"<option>Select an option</option>"; // <===========================
while ($tempCount < $count) {
$tempCount++;
echo "<option value='$tempCount'>$tempCount</option>";
}
echo "</select>";
echo "</form>";
}
limit(5,"xyz.php");
if ( isSet( $_POST['value'] ) ) // <===========================
{ $value = $_POST['value'];
echo $value;
}
?>
选项&#34;选择一个选项&#34;将让用户选择选项1。
如果您不想看到&#34;选择一个选项&#34;,另一个解决方案是选择所选的选项,例如,如果用户选择&#34; 3&#34; ,当页面重新加载选项&#34; 3&#34;将被选中,用户将能够选择选项&#34; 1&#34; :
<?php
function limit($count,$location) {
echo "<form method = 'POST' action = '$location'>";
echo "<select name = 'value' onchange='this.form.submit()'>";
while ($tempCount < $count) {
$tempCount++;
// MAKE THE CURRENT OPTION SELECTED IF IT WAS CHOSEN BEFORE. <==========
if ( isSet( $_POST['value'] ) && // IF 'value' EXISTS, AND
( $_POST['value'] == $tempCount ) ) // IF 'value' == CURRENT NUMBER
$selected = "selected";
else $selected = "";
echo "<option $selected value='$tempCount'>$tempCount</option>";
}
echo "</select>";
echo "</form>";
}
limit(5,"xyz.php");
if ( isSet( $_POST['value'] ) ) // <===========================
{ $value = $_POST['value'];
echo $value;
}
?>