Reputation: 7
I am creating a editing of account information form.php Here i have a nationality input where user can change their nationality.
The question- Lets say i am from Afghanistan. How do i make it the default option when i have clicked the "EDIT" button? Using IF statement ($nationality== __) ? any idea?
$nationality = $row["nationality"];
<select name="nationality">
<option value="Afghanistan">Afghanistan (افغانستان)</option>
<option value="Åland Islands">Åland Islands (Åland)</option>
<option value="Albania">Albania (Shqipëria)</option>
<option value="Algeria">Algeria (الجزائر)</option>
<option value="American Samoa">American Samoa</option>
<option value="Andorra">Andorra</option>
<option value="Angola">Angola</option>
</select>
Upvotes: 0
Views: 1041
Reputation: 4930
To have an option automatically selected, you give it the "selected" attribute.
If present, this Boolean attribute indicates that the option is initially selected. If the element is the descendant of a element whose multiple attribute is not set, only one single of this element may have the selected attribute.
So, in each option, you could do something similar to
<option value="Afghanistan" <?php echo ($nationality === 'Afghanistan' ? 'selected' : '')?>>Afghanistan (افغانستان)</option>
It would be easiest to do if you have an array of countries instead of printing each one out by hand.
$countries['Afghanistan'] = 'Afghanistan (افغانستان)';
$countries['Åland Islands'] = 'Åland Islands (Åland)';
$countries['Albania'] = 'Albania (Shqipëria)';
$countries['Algeria'] = 'Algeria (الجزائر)';
$countries['American Samoa'] = 'American Samoa';
$countries['Andorra'] = 'Andorra';
$countries['Angola'] = 'Angola';
foreach ($countries as $name=>$full_name) {
$selected = ($nationality === $name) ? 'selected' : '';
print '<option value="'.$name.'" '.$selected.'>'.$full_name.'</option>';
}
Upvotes: 2
Reputation: 5766
If the server knows the appropriate default option when it outputs the page, then you can just conditionally add the selected
attribute to the HTML you emit:
<option value="Afghanistan" selected="selected">Afghanistan (افغانستان)</option>
Upvotes: 0