Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get selected option text onChange

Tags:

angular

I know how to get the selected option value when a select changes (as shown below), but how do I get the displayed text of the selected option?

Template:

<select (change)="onChange($event.target.value)">
    <option *ngFor="let option of activeDropdown.options" value="{{option.value}}">
        {{option.text}}
    </option>
</select>

Component:

onChange(value: string) {
    console.log(value);
}

Thanks!

like image 745
goodoldneon777 Avatar asked Oct 30 '16 19:10

goodoldneon777


People also ask

How do I get the selected text option?

Or to get the text of the option, use text() : $var = jQuery("#dropdownid option:selected"). text(); alert ($var);

How do I get a dropdown selected value and text?

We can select text or we can also find the position of a text in a drop down list using option:selected attribute or by using val() method in jQuery. By using val() method : The val() method is an inbuilt method in jQuery which is used to return or set the value of attributes for the selected elements.

How do I get the text value of a selected option JavaScript?

Use the selectedIndex Property We can get the index of the selected item with the selectedIndex property. Then we can use the text property to get the text of the selected item. We create the getSelectedText function that takes an element as the parameter. Then we check if selectedIndex is -1.


3 Answers

getSelectedOptionText(event: Event) {
   let selectElementText = event.target['options']
      [event.target['options'].selectedIndex].text;
      console.log(selectElementText);                                 
}

HTML

<select name="" ngModel (change)="getSelectedOptionText($event)">
  <option *ngFor="let item of items" [value]="item.id">{{item.name}}
  </option>
</select>
like image 52
Mahendra Waykos Avatar answered Oct 17 '22 16:10

Mahendra Waykos


On Angular 6 this worked for me:

let text = event.target.options[event.target.options.selectedIndex].text;
like image 42
D. K. Avatar answered Oct 17 '22 16:10

D. K.


You should pass an object to ngValue and use ngModel:

@Component({
  selector: 'my-app',
  template: `
    <div>
     <select [ngModel]="active" (ngModelChange)="onChange($event)">
       <option *ngFor="let option of activeDropdown.options" [ngValue]="option">
        {{option.text}}
       </option>
     </select>
    </div>
  `,
})
export class App {
  activeDropdown;
  constructor() {
    this.active = {};
    this.activeDropdown = {
      options: [{text: 'One', value: 1}, {text: 'Two', value: 2}]
    }
  }

  onChange(event: string) {
    console.log(event.text);
}
}

Plunker

like image 42
Bazinga Avatar answered Oct 17 '22 14:10

Bazinga