Reputation: 10179
I have a list of cities.
<select name="cities">
<option value="nc">New city..</option>
<option value="quetta">Quetta</option>
<option value="karachi">Karachi</option>
<option value="islamabad">Islamabad</option>
<option value="khyber pukhtun khuan">Khyber Pukhtun Khuan</option>
<option value="multan">Multan</option>
<option value="murree">Murree</option>
<option value="gwadar">Gwadar</option>
<option value="gujranwala">Gujranwala</option>
<option value="faisalabad">Faisalabad</option>
<option value="peshawar">Peshawar</option>
</select>
And i have a database in which i have stored user's city. Now i am making a page in which the user will update his city and for that i want the user to see his city already selected when he opens up the page. In short, i want a option to be selected according to the value returned by the database. I am using php as the language
I have got one solution but not implemented it yet because its not effecient! Any easy and effecient way would be appreciated.
Thanks in advance :)
Upvotes: 1
Views: 1159
Reputation: 5896
One possible solution could be to change your code structure to something more along the lines of:
// hardcoded cities or perhaps loaded from elsewhere
$cities = [
"nc" => "New city...",
"quetta" => "Quetta",
"karachi" => "Karachi"
// ...
];
// user's city fetched from the database
$userCity = "quetta";
echo '<select name="cities">';
foreach ($cities as $key => $value)
{
echo '<option ' . ($userCity === $key ? 'selected' : '') . ' value="' . $key . '">' . $value . '</option>';
}
echo '</select>';
Upvotes: 0
Reputation: 9713
//first you have a specific city of a user
$user_city = 'city-name';
//Then you have a list of all cities available (probably from the database,
// but I use array here as an example)
$cities = array('city1','city2','city3');
<select name="cities">
<?php
foreach ( $cities as $city ) {
if ( $city == $user_city ) {
echo "<option value='".$city."' selected>$city</option>";
} else {
echo "<option value='".$city."'>$city</option>";
}
}
?>
</select>
Upvotes: 4
Reputation: 943567
Get your list of cities into an array instead of hard coded HTML.
Loop over the list and output the option
element for each.
As you do so, compare to the value retrieved from the database. Add selected
if they match.
Upvotes: 1
Reputation: 601
just check the value from database and add selected to that option by using javascript or php
<option value="murree" selected >Murree</option>
Upvotes: 1