how to add onchange event on dropdown in angular ? - javascript

could you please tell me how to add onchange event on dropdown in angular ? I made a simple demo in which initially I fetch bank names and show in drop down . Now I want to add on change event on that dropdown .In other words I want to which bank user select . Using that bank name I want to get state names
here is my code
https://stackblitz.com/edit/angular-batt5c
<select class='select-option'
(ngModelChange)='onOptionsSelected($event)'>
<option class='option'
*ngFor='let option of dropDownData'
[value]="option.seo_val">{{option.text_val}}</option>
</select>
onOptionsSelected(){
console.log('===');
// send selected value
this.seletedValue.emit('');
}

Use (change) event instead of (ngModelChange).
<select class='select-option'
#mySelect
(change)='onOptionsSelected(mySelect.value)'>
<option class='option'
*ngFor='let option of dropDownData'
[value]="option.seo_val">{{option.text_val}}</option>
</select>
In typescript file:
onOptionsSelected(value:string){
console.log("the selected value is " + value);
}

try this.
<select class='select-option' [(ngModel)]="selected"
(change)='onOptionsSelected($event)'>
<option class='option' *ngFor='let option of dropDownData'
[value]="option.seo_val">{{option.text_val}}</option>
</select>
public onOptionsSelected(event) {
const value = event.target.value;
this.selected = value;
console.log(value);
}

Related

How to show and hide the content based on dropdown selection items in angular

My requirement is to show the content based on selection of dropdown list.
component.ts
OptionList: LookupActionCode[]=[];
public setList(actionType: any):void{
this.anotherOptionList = [];
if(actionType == dataConstant.calendar){
this.List.push(
{
Name: dataConstant.content
},
{
Name: dataConstant.showcontent
},
{
Name: dataConstant.hidecontent
},
)}
switch(actionType){
case dataConstant.memberdata:
this.OptionList = this.memberCodes;
break;
case dataConstant.referral:
this.OptionList= this.optionalCodes;
break;
case dataConstant.Calendar:
this.OptionList = this.List;
break;
}
.component.html
//first dropdown
<label for="OptionList" class="cpp-required"> <b>Action</b></label>
<select id=action class="form-control" required (change) ="setList($event.target.value)">
<option value="" disabled [selected]="true"></option>
<option [value] = "dataConstant.referral">{{dataConstant.referral}}</option>
<option [value] = "dataConstant.memberdata">{{dataConstant.memberdata}}</option>
<option [value] = "dataConstant.calendar">{{dataConstant.content}}</option>
</select>
//second dropdown
<label> <b>Action</b></label>
<select id=action class="form-control" required>
<option value="" disabled [selected]="true"></option>
<option *ngFor="let option of optionList" [value] ="option">{{option.Name}} </option>
</select>
<div *ngIf="logic>
//some content to show and hide the data
</div>
So my requirement is from the first dropdown if i select the dataConstant.content then In secondit will show the realted dropdown lists those are dataConstant.content,dataConstant.showcontent and dataConstant.showcontent (implemented)
So If select the dataConstant.showcontent value then I need to show the data in div
Can anyone help me on this
If you first add a property to your component in ts to hold the selected value:
theProperty: string | undefined;
and on your select list in html add:
<select [(ngModel)]="theProperty" ect...
This will set up two way binding between your property and the select list. (Note reactive forms are good option here but have chose this for simplicity).
You can then add:
*ngIf="theProperty === thingToMatchTo"
But maybe pick a more sensible property name than what I've used.
NOTE - Make sure you add FormsModule to your imports in the Module that this component is declared. It's what makes the ngModel directive available to you.

How to save select dropdown menu option in HTML/pure JS?

Let's say I have this code:
<select id = dropdown-list>
<option value = "0"> Yes </option>
<option value = "1"> No </option>
</select>
The user can select yes or no from a dropdown list. How can I use pure JS/HTML to figure out what the user has selected (and is currently showing in the dropdown list box when the list isn't expanded) so I can use that data elsewhere? The only way I can figure out is if I add an eventListener on each option but I feel there is a better way. I am quite new to JS so I'm not sure. Thank you.
You can use onchange attribute from select element.
<select id="dropdown-list" onchange="onChange(this.value)">
<option value = "0"> Yes </option>
<option value = "1"> No </option>
</select>
and in JS:
function onChange(val) {
// `val` is the value
}
Execute a JavaScript function changeResult when a user changes the selected option of a element:
Flow:
We bind changeRegult using onchange event listener.
When we change the dropdown menu, it calls changeResult function.
Inside the function, we select our dropdown menu using its id property.
After getting the element by id, we can now access all properties.
Here we want to show the value property, so we use document.getElementById("dropdown-list").value.
For more check this link.
function changeResult() {
var x = document.getElementById("dropdown-list").value;
document.getElementById("result").innerHTML = "You selected: " + x;
}
<select id = "dropdown-list" onchange="changeResult()">
<option value = "0"> Yes </option>
<option value = "1"> No </option>
</select>
<p id="result"></p>
You may want to use on change event.
Since you use each I suppose you are using Jquery.
If you have any question just let me know.
$(document).ready(function(){
$('#dropdown-list').on('change',function(){
alert($(this).children('option:selected').val());
})
});
https://jsfiddle.net/u4dz162o/

selected in select option give wrong attribute value

I want to display a select with all the option of my enum and change the value to update my database.
To do so:
I have an enum:
export enum SubscriptionEnum {
DAILY= 'DAILY',
ANNUAL= 'ANNUAL',
HALF-YEARLY = 'HALF-YEARLY ',
QUARTERLY = 'QUARTERLY ',
MONTHLY = 'MONTHLY ',
}
In my .ts file i create my enum var:
SubscriptionEnum = SubscriptionEnum ;
And then i display the option in my .html:
<p>{{client.subscription}}</p> // here it display what is registered in my db, in this case "ANNUAL"
<label for="subscription">Subscription:</label>
<select #subscriptionid="subscription">
<option value="{{option.key}}"
*ngFor="let option of SubscriptionEnum | keyvalue">
{{option.value}}
</option>
</select>
This example give me the select with all option and the value change in the view page when i clicked on a new option.
Then, i add the (change) in the select to call a method that change the content of the client subscription in the db. I did it like that:
.html:
<p>{{client.subscription}}</p> // here it display what is registered in my db, in this case "ANNUAL"
<label for="subscription">Subscription:</label>
<select (change)="changeInfo(subscription )" #subscription id="subscription">
<option value="{{option.key}}"
*ngFor="let option of SubscriptionEnum | keyvalue">
{{option.value}}
</option>
</select>
In my changeInfo i send the event and take the event.id and the event.value to update my db and it works because the select option change when i click on it and the <p>{{client.subscription}}</p> that is a value of my db take the good value.
Then i wanted to add a selector so my option value take directly the good value and this is not working ...
I add it like that:
<p>{{client.subscription}}</p> // here it display what is registered in my db, in this case "ANNUAL"
<label for="subscription">Subscription:</label>
<select (change)="changeInfo(subscription )" #subscription id="subscription">
<option value="{{option.key}}"
selected="{{option.key == client.subscription}}"
*ngFor="let option of SubscriptionEnum | keyvalue">
{{option.value}}
</option>
</select>
This give highlight me my sentence and tell me "Wrong attribute method" and when i reload my page my div contains the good value which is "ANNUAL" but my option is equal to QUARTERLY. If i click to change the option, the good value will be saved in my db but the display of my select selector will be wrong.
What do i not understand ? Thank you for your help
There is a subtle difference between two similar Angular syntaxes:
selected="{{option.key == client.subscription}}"
and
[selected]="option.key == client.subscription"
There are both property bindings but the former assigns interpolated value to property.
It means that even in case of falsy values selected property will get true;
el.selected = 'false'
because string is a truthy value in js.
So you can consider the following options:
Use correct property binding:
[selected]="option.key == client.subscription"
Use value binding on <select> tag instead:
<select #subscription id="subscription" [value]="client.subscription">
<option value="{{option.key}}"
*ngFor="let option of SubscriptionEnum | keyvalue">
{{option.value}} {{option.key == client.subscription}}
</option>
</select>

javascript Trying to copy database generated text in selectbox to textbox

I'm trying to make a chained dropdown that contain continent, region,country, province,city,district, and village, but i'm stuck at country.
my dropdown require me to use the id from database to chain all the dropdown, so to get the text name i usually using this method :
Country :
<select name="loc_country" class="loc_country loc5" id="loc_country" onchange="javacript: var valor2 = this.options[selectedIndex].text; document.getElementById('loc_country_real').value = valor2;">
<option value="0">-Select-</option>
</select>
<input type="text" id="loc_country_real" name="loc_country_real">
However this method doesn't work this time so i try another approach with :
<select name="loc_country" class="loc_country loc5" id="loc_country">
<option value="0">-Select-</option>
</select>
<input type="text" id="loc_country_real" name="loc_country_real">
and js :
$("#continent").change(function () {
$("#loc_country_real").val($('#loc_country').text());
});
and hoping when my select box with id="continent" changing, the value will update.
And that method also failed because the value given in "loc_country_real" doesn't match with selectbox "loc_country" (e.g.:when i selected europe on the continent selectbox, the loc_country select box will give me a list of european countries but the value in "loc_country_real" will be asian from country)
i need to make the text in "loc_country" and "loc_country_real" match but i have no idea how to do it, please help.
Try this:
Change your select's to have a VALUE matching the text you want E.G:
<select name="loc_country" class="loc_country loc5" id="loc_country">
<option value="0">--Select--</option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
<option value="Mexico">Mexico</option>
</select>
You can then use document.getElementById('loc_country').value to get the selected option value
// Change `loc_country_real`'s value to match `loc_country` selected option
document.getElementById('loc_country_real').value = document.getElementById('loc_country').value;
Or the jQuery way:
$('#loc_country').change(function(){
$('#loc_country_real').val($('#loc_country').val());
});
Edit since you mentioned you cannot use value:
$('#loc_country').change(function(){
var textOfSelectedOption = $("#loc_country option:selected").text();
$('#loc_country_real').val(textOfSelectedOption);
});

Angular: dynamic value issue

I am trying to show different data from a large data object based on selections made in view via a select box. I am populating the data like this
$scope.displayData = $scope.dataObj[$scope.selectedType][$scope.networkType];
And I have ng-model on my select options.
<select ng-model="networkType">
<option value="networkOne">One</option>
<option value="networkTwo">Two</option>
<option value="networkThree">Three</option>
</select>
<select ng-model="selectedType">
<option value="typeOne">One</option>
<option value="typeTwo">Two</option>
<option value="typeThree">Three</option>
</select>
I initialize both of these variables
$scope.selectedType = 'individual';
$scope.networkType = 'inNetwork';
And the $scope.displayData is initially correct. However when I change the drop downs, the displayData does not change its values to access the new data. I am not sure what step I am missing here.
I think you should update the display data using ng-change event.
Add a update function in your controller
$scope.updateDisplay = function() {
$scope.displayData = $scope.dataObj[$scope.selectedType][$scope.networkType];
};
Add ng-change for your <select> element
<select ng-model="networkType" ng-change="updateDisplay()">
<option value="networkOne">One</option>
<option value="networkTwo">Two</option>
<option value="networkThree">Three</option>
</select>
<select ng-model="selectedType" ng-change="updateDisplay()">
<option value="typeOne">One</option>
<option value="typeTwo">Two</option>
<option value="typeThree">Three</option>
</select>
Or do it with $scope.$watch.
The $scope.watch() function creates a watch of some variable. When you register a watch you pass two functions as parameters to the $watch() function:
A value function
A listener function
The first function is the value function and the second function is the listener function.
The value function should return the value which is being watched. AngularJS can then check the value returned against the value the watch function returned the last time. That way AngularJS can determine if the value has changed.
In my example, we are setting up a watch on both networkType and selectedType models. And instead of it being a funtion we simply put the $scope model name.
$scope.$watch('[networkType,selectedType]', function(newValues, oldValues) {
$scope.displayData = $scope.dataObj[newValues.selectedType][newValues.networkType];
});
Add this method to your controller
$scope.onChnage = function () {
$scope.displayData = $scope.dataObj[$scope.selectedType][$scope.networkType];
}
Html
<select ng-model="networkType" ng-change="onChnage ()">
<option value="networkOne">One</option>
<option value="networkTwo">Two</option>
<option value="networkThree">Three</option>
</select>
<select ng-model="selectedType" ng-change="onChnage ()">
<option value="typeOne">One</option>
<option value="typeTwo">Two</option>
<option value="typeThree">Three</option>
</select>
Beside $watch and ng-change, if you just want to display the data in displayData variable, another option is to convert it to a function display():
$scope.display = function () {
return $scope.dataObj[$scope.selectedType][$scope.networkType];
};
and in the view:
{{display()}}
this function will be called again whenever selectedType or networkType change

Categories