'How to keep value of selected value after form submission?
I know there are a lot of questions related to it but believe me, no solution is working for me.
<form action="index" method="post" >
<select id="s" name="dtype" class="dropdown" required
style="float: left; text-align: left;width: 20%; margin: 10px;">
<option value="400">Select Data Type</option>
<option value="401">Current</option>
<option value="402">Voltage</option>
<option value="403">kWh</option>
</select>
</form>
What I have tried
I have tried the following
<option <?php if ($_GET['dtype'] == '401') { ?>selected="true" <?php }; ?>value="401">Current</option>
<option <?php if ($_GET['dtype'] == '402') { ?>selected="true" <?php }; ?>value="402">Voltage</option>
<option <?php if ($_GET['dtype'] == '402') { ?>selected="true" <?php }; ?>value="402">kwh</option>
Tried below solution
All the solution gives me unidentified index: dtype
error
Any help would be highly appreciated.
Solution 1:[1]
In your form you have: method="post"
And then you use the $_GET['dtype']
Either change the method of the form to method="get"
or change the if conditions to check for $_POST['dtype']
.
That's why it says unidentified index. You are sending the data as post and trying to get it from the $_GET array.
Apart from this, if you are using xhtml the attribute value should be selected="selected"
whereas if you use an html 5 doctype it should be just selected
.
Solution 2:[2]
The first option (Select Data Type) must have an empty value in order for "required" option to work.
<form action="index.php" method="POST">
<select id="s" name="dtype" class="dropdown" required style="...">
<option value="">Select Data Type</option>
<option value="401" <?php if(isset($_POST['dtype']) && $_POST['dtype']=="401") {echo'selected';} ?>>Current</option>
<option value="402" <?php if(isset($_POST['dtype']) && $_POST['dtype']=="402") {echo'selected';} ?>>Voltage</option>
<option value="403" <?php if(isset($_POST['dtype']) && $_POST['dtype']=="403") {echo'selected';} ?>>kWh</option>
</select>
</form>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | George |