Select2 multiple select default selections not working - javascript

This is my html code
<select name="age_group[]" class="form-control age_group" multiple="multiple">
#foreach($age_groups as $group)
<option value="{{ $group->id }}">{{ $group->age_group_name }}</option>
#endforeach
</select>
And this is the JS
var selected = [1, 2, 3];
// initialize select2 for age group
$(".age_group").select2();
$(".age_group").select2('val', selected);
What I want to do is set default values as selected as suggested by this post. But in my code above I am only getting the first element of the array as selected.
Can anyone tell me what's wrong with my code?
Jsfiddle demo

Try like this it will work:
$(".age_group").val(selectedvalue).trigger("change");
sample fiddle : http://jsfiddle.net/fyhsz9ra/891/

You need to specify the value you need to select.
$('select').select2().select2('val', $('.select2 option:eq(1)').val());
OR
Split the values before Passing to the Select2();
var values = //split the string ;
$(".age_group").select2('val',values);
Hope this Helps you.

Related

Select first element in dropdown in Angular 7

I am getting content of dropdown list as a Map<number, string>. When I get the map, it is received sorted according to keys in ascending order.
While showing it in html, I am setting pipe keyvalue and provided a function to sort the items in ascending order of values.
Now, I am trying to select first element of this dropdown, but unable to do so.
I have tried jQuery method to select the first element.
I have tried to set ngModel of the select box to first value of the map, but it sets the value to the first value received in the Map which is sorted by key.
My HTML:
<select class="form-control" id="empId" [(ngModel)]="empId" [disabled]="!isEditable">
<option *ngFor="let emp of empNames | keyvalue:descOrder" [value]="emp.key">{{ emp.value }}</option>
</select>
My ts file:
this.commonService.getEmployeeList())
.subscribe((response) => {
this.empNames = response;
this.empId = this.empNames.keys().next().value;
});
data I am sending from server is:
{id:1,name: "Tim"},
{id:6,name: "Martha"},
{id:5,name: "Alex"},
{id:8,name: "Stacy"}
data I am receiving on screen is like:
Alex
Martha
Stacy
Tim
with Tim pre-selected
what I need is Alex should be pre-selected.
Then set the empId before subscribing.
this.empId = 5;
this.commonService.getEmployeeList())
.subscribe((response) => {
this.empNames = response;
});
Of course you might want another logic based on some kind of order. You can never be sure how the data are going to be received.
In this case you need to send the order from your api and filter by order.
Working Demo
<option *ngFor="let emp of empNames | keyvalue:descOrder" [value]="emp.key" [selected]="emp.id === 1">{{ emp.value }}</option>
you can use selected attribute like above
I would highly recommand you to use Angular's reactive forms! And set the select's value to the one you want, when you recieve your data. Don't use ngModel as it is deprecated and should have been removed by Angular 7 (Or will be soon). Check this
The best way to pre select an option is to use ngModel as you tried. Your list is sorted by keys so what you want is not to select the first item, yes it's the first but in other order so or you change the order in code or you search for the item you want to select and stores it to set on model.
I would suggest some changes that should improve the code and fix your problem.
<select class="form-control" id="empId" [(ngModel)]="currentEmployer" [disabled]="!isEditable">
<option *ngFor="let emp of employers$ | async" [value]="emp">{{ emp.value }}</option>
</select>
And order your list in a pipe with the function you prefer.
public currentEmployer: Employer = null;
private sortByNameAscending(e1, e2) {
return e1.name > e2.name ? 1 : 0;
}
this.employers$ = this.commonService.getEmployeeList().pipe(
switchMap(employers => {
const sortedList = employers.sort(this.sortByNameAscending);
if (sortedList.length > 0) {
this.currentEmployer = sortedList[0];
}
return sortedList;
})
);

ng-selected with ng-repeat in select

Sorry for asking again . But I cant set default value for select . Here is code I used
Plnkr
I cant use ng-options in this case . Please help me without ng-options
If the model has the value same as option defined, ng-selected would work as:
ng-selected="business_entity == businessConstants"
given the model is such :
$scope.formData = {business_entity : 'Công ty TNHH'};
Forked Plunker
Try to use the code in your controller as below,
$scope.formData={};
$scope.formData.business_entity = 'Công ty TNHH';
And please remove 'ng-selected' from your option tag from your tempalte.
<select ng-model="formData.business_entity">
<option ng-repeat="businessConstants in businessConstants" value="{{businessConstants}}">
{{businessConstants}}
</option>
</select>
I've update your plnk please check..
remove ng-select and assign array reference to ng-model variable
$scope.formData = {
'business_entity' : $scope.businessConstants[1]
}
Html
<select name="" id=""
ng-model="formData.business_entity">
<option
ng-repeat="businessConstants in businessConstants"
value="{{businessConstants}}">
{{businessConstants}}
</option>
</select>
Demo
Change your HTML to
<body ng-controller="ctrl">
<select name="" id=""
ng-options="option for option in businessConstants"
ng-model="business_entity">
</select>
</body>
Your options will be automatically generated and the select will be bound to business_entity automatically
Change Controller to
function ctrl($scope) {
$scope.businessConstants = [
'Công ty Cổ phần',
'Công ty TNHH',
'Tổ chức nhà nước',
'Ngân hàng',
'Trường học',
'Cá nhân',
'Khác'
];
$scope.business_entity = $scope.businessConstants[4];
}
This will set the default value. Make sure you select the default value from the existing collection businessConstants and not assign it.
You can refer updated Plunker link

ng-options based on previous selected value

I have an array like below.
$scope.set = [
{"name":"name1", "value":"value1"}
{"name":"name2", "value":"value2"}
{"name":"name3", "value":"value3"}
]
I am trying to show the options based on previous selection. for example if i select name1 then for the next time i don't want to show the selected option. I want to show only remaining two names i.e, name2 and name3.
I'm trying to achieve this by using some filters but it is effecting the model $scope.set
Please help me in this. thanks in advance.
A possible solution for you problem can be found here on Fiddle. I've created something quickly from scratch since your post did not have an original Fiddle.
<div ng-app ng-controller="Controller">
Select value : <b>{{myDropDown.name}}</b><br/><br/>
Showing all other available options:
<select ng-options="item.name for item in items | filter: {name: '!' + myDropDown.name}" ng-model="myDropDown">
<option value="">Select other value</option>
</select>
</div>
function Controller ($scope) {
$scope.myDropDown = 'one';
$scope.items = [
{"name":"name1", "value":"value1"},
{"name":"name2", "value":"value2"},
{"name":"name3", "value":"value3"}
];
}

Make dropdown multi-select

I have 2 dropdowns and one of them(the second one) is dynamic in the sense that its values change according to the option chosen in the first dropdown.
JSFiddle result: http://jsfiddle.net/pgbw56vb/10/embedded/result/
Can someone pls show me how i can make the second dropdown a multi-select? I'm really green in Jquery and html.
JSFiddle: http://jsfiddle.net/pgbw56vb/10/
<select id="kategorie_oder_seite"></select>
<select id="auswahl"></select>
var data = {
"Kategorie": ["Kraft", "Startseite", "Insurance", "Risk",],
"Seite": ["http://jsfiddle.net/tony089/pgbw56vb/2/", "https://stackoverflow.com/users/login?returnurl=%2fquestions%2fask"],
};
var $kategorien = $("#kategorie_oder_seite").on("change", function() {
var seiten = $.map(data[this.value], function(seite) {
return $("<option />").text(seite);
});
$("#auswahl").empty().append(seiten);
});
for (var kategorie in data) {
$("<option />").text(kategorie).appendTo($kategorien);
}
$kategorien.change();
Thanks in advance.
you can use the multiple attribute of select tag and set its value to multiple. also remember to set the name property in array form so that you could send multiple values via this select control.
eg.
<select multiple="multiple" id="kategorie_oder_seite" name="check[]"></select>
JsFiddle: http://jsfiddle.net/pgbw56vb/10/
just add "multiple" attribute on the "select" tag
Add multiple to your select tags.
<select id="kategorie_oder_seite" multiple></select>
<select id="auswahl" multiple></select>

Can't remove blank select <option> created by ng-repeat in AngularJS

This is a common problem however when trying to use the solutions provided here on Stackoverflow I am having no success... I have the following in my HTML view:
<select class="date-input" ng-model="reservation.date">
<option ng-repeat="d in dates track by $index"
value="{{ d }}"
> {{ d }} </option>
</select>
In my controller I have the following...
$scope.makeDates = (function () {
dArray =[];
// we make a big array of dates ['dd-mm-yyyy','dd-mm-yyyy', 'dd-mm-yyyy'...] for 3 months and return it
return dArray;
}();
$scope.reservation = {
date : null,
time : null,
quantity : null
};
$scope.dates = $scope.makeDates;
$scope.reservation.date = $scope.dates[0];
However despite me setting $scope.reservation.date = $scope.dates[0]; the select still produces a blank option and is the default/selected value!?!?! Am I missing something? I know it is early but I can't see what I am doing wrong?
You don't need attribute value="{{ d }}" for <option>. This is a reason why you get empty item.
HTML
<div ng-app='myApp' ng-controller="ArrayController">
<select class="date-input" ng-model="reservation.date">
<option ng-repeat="d in dates track by $index">{{d}}</option>
</select>
</div>
Demo Fiddle

Categories