Reputation: 2659
I'm using a select list function below to make a select list that have 5 values inside of it. Values 2-5 works fine when I select them, and they print out their values on the page when I select them, but value 1 does not print out no matter what. I cannot figure out what I did wrong or how to fix it. Please take a look at my code:
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;
Upvotes: 0
Views: 358
Reputation: 10381
Add one first option to the < select >
, and, check if $_POST['value']
exists. Next is your code with both changes pointed by commented arrows (//<=====) :
<?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;
}
?>
The option "Select an option" will let the user to choose option 1.
If you don't want to see "Select an option", the other solution is to make the chosen option selected, for example, if the user chooses "3", when the page reloads the option "3" will be selected, and the user will be able to choose option "1" :
<?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;
}
?>
Upvotes: 1