Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropdown not working as expected in Safari?

I have a dropdown in an Angular 2 project:

<div class="form-group">
   <label for="vendors">Vendors</label>
   <select class="form-control" id="vendor_id" name="vendor_id" [(ngModel)]="selectedVendor"  (ngModelChange)="onVendorChange($event)" required>
      <option *ngFor=" let vendor of vendors " [ngValue]="vendor"> {{vendor.business_name}} </option>
   </select>
</div>

This works fine in Chrome, but when I open it in Safari, when the page is loaded it shows the first item as selected even if I didn't selected anything. However, if I click "Submit" it will show "This field is mandatory".

In Safari it shows the first item as selected, but actually it's not selected. How to fix this?

like image 754
hilda_sonica_vish Avatar asked Jun 09 '17 05:06

hilda_sonica_vish


2 Answers

In fact, you may find that the accepted answer is insufficient. At least using Angular 5 and Safari, I have found that you must explicitly make the option undefined. In other words:

 <option disabled selected value=undefined> --Select-- </option>

Otherwise, the option will simply be marked as disabled and Safari will continue to show that it has the first real option selected, when in fact it isn't (and can't be).

like image 89
David Hoelzer Avatar answered Sep 30 '22 17:09

David Hoelzer


This is not an angular issue, this is the default behavior on safari/mobile safari. An easy solution/workaround is shown below.

If you add another option box such as:

<option disabled selected value> --Select-- </option>

Then your code becomes:

<div class="form-group">
    <label for="vendors">Vendors</label>
    <select class="form-control" id="vendor_id" name="vendor_id" [(ngModel)]="selectedVendor"  (ngModelChange)="onVendorChange($event)" required>
        <option disabled selected value> --Select-- </option>
        <option *ngFor=" let vendor of vendors " [ngValue]="vendor"> {{vendor.business_name}} </option>
    </select>
</div>

This way you cannot re-select the first "Select" box after the user has made a valid selection, answer taken from this answer.

like image 34
crooksey Avatar answered Sep 30 '22 17:09

crooksey