How to set selected values on multiple select2? - javascript

I have a multiple select2 input. I am populating all necessary options into it. After that I am sending selected values to it but these selected values are not marked on UI.
I tried below code blocks but not working either of them.
let array = [];
data.jobDepartments.map(x => {
array.push(x.id);
});
$("#jobDepartment").val(array).trigger("change");
let array = [];
data.jobDepartments.map(x => {
array.push(x.id);
});
$("#jobDepartment").select2("val", array);
Here is my settings for select2 input.
<select id="jobDepartment" name="jobDepartment" class="form-control select2" multiple="multiple" data-toggle="tooltip" data-trigger="hover" data-placement="top" data-title="jobDepartment"></select>
$(document).ready(function () {
$(".select2").select2();
});
let array = [];
data.jobDepartments.map(x => {
array.push(x.id);
});
$("#jobDepartment").val(array).trigger("change");
Result is: https://prnt.sc/pn0v94
I was expecting this: https://prnt.sc/pn0vvb
Could you help me with it?

Try this Fiddle
Following things are missing in your code:
you should have data config while creating select2
$("#e9").select2({
placeholder: "Select a State",
allowClear: true,
templateSelection:function(obj){
return obj.title;
},
data: [{
'id': 1,
title: 'test'
}, {
'id': 2,
title: 'test1'
}
]
});
then you have fire your change

I solved the problem. Mistake was coming data. My data id was wrong.

Related

Select2 ajax preselection with custom data value

So I have a multiselection dropdown with select2 and I fetch the info from a database. The thing is that prepopulating the dropdown with many values works with the example from the docs, but I also want to include an extra data field. This is how I try to populate the dropdown:
var productSelect = $('#product_ids');
$.ajax({
type: 'GET',
url: '/ajaxOrdersData/' + orderID
}).then(function (datas) {
datas.forEach(data => {
var option = new Option(data.name, data.id, true, true);
option.dataset.price = data.price;
productSelect.append(option).trigger('change');
});
productSelect.trigger({
type: 'select2:select',
params: {
data: datas.map(function (item) {
return {
text: item.nfame,
id: item.id,
price: item.price,
}
})
}
});
});
The above code does create an option tag with a data-price value but then, retrieving that value like below, doesn't work:
var products = $('#product_ids').select2('data');
The products variable doesn't have the price data attribute.
What other ways there are for me to fetch the price data attribute of all products in multiselect when clicking on a button on the DOM?
This is a solution I came up with:
var products =$('#product_ids option:selected');
And then to retrieve the value:
$.each(products, function(index, value) {
actualTotals += Number(value.dataset.price);
});
An alternative solution is to keep the .select2('data'); way of fetching the selections but instead use jquery to retrieve each elements attributes from the resulting object:
var products =$('#product_ids').select2('data');
$.each(products, function(index, value) {
price = value.element.attributes['data-price'].value;
});

How to solve "of undefined" problem of a service?

I am calling service in Angular7 at every dropdown option change. But when I change selected option on dropdown I am getting getAllByCountryId of undefined error.
Here is function that calling http service:
countryOnChange(countryId: Guid) {
this.cityService.getAllByCountryId(countryId).subscribe(
res => {
if (res.code === ResponseCode.success) {
res.dataList.map(item => {
this.cities.push({
value: item.id.toString(),
label: item.dataValue
});
});
if (this.formComponent !== undefined) {
this.formComponent.form.controls['cityId'].patchValue(this.cities);
}
}
},
err => {
this.error = true;
});
}
Here is the HTML code that calling above function on every dropdown option change:
<ng-container *ngSwitchCase="'dropdown'" class="col-md-12">
<ng-select [ngClass]="'ng-select'" [options]="input.options" [formControlName]="input.key" [id]="input.key" (selected)="input.onChange($event.value)"></ng-select>
</ng-container>
input.onChange($event.value) and countryOnChange is connected at the backend.
Here is how to call countryOnChange function:
const dropdown2 = new InputDropdown({
key: 'countryId',
label: '',
onChange: this.countryOnChange,
options: this.countries,
value: '',
required: true,
order: 3
});
Error http://prntscr.com/ovjxe7
How can I solve this problem?
I think [ngModel] is needed:
<select [ngModel]="selectedValue" (ngModelChange)="onDropdownChange($event)"
class="form-control">
<option *ngFor="let category of categorylist" [ngValue]="category.id">
{{category.Description}}</option>
</select>
refer to: Angular 2 How to bind selected id in Dropdownlist with model?
getAllByCountryId of undefined error means you are getting this.cityService as undefined.
Check with which this context your function is binding when you are creating the InputDropDown. May be you need to define it like :-
const dropdown2 = new InputDropdown({
key: 'countryId',
label: '',
onChange: this.countryOnChange.bind(this),
options: this.countries.bind(this),
value: '',
required: true,
order: 3
});
Hope this helps.

Cannot select default value in dropdown using ng-model and ng-repeat or ng-select in AngularJS

i'm really new to AngularJS and i like it very much.
But i'm experiencing a problem trying to initialize a prealoaded dropdown with a specific value.
The dropdown is initialized with values available from JSON array, but when i try to select a default value in this dropdown, i don't see that value selected but the ng-model variable is set correctly.
I created a plunker example here http://plnkr.co/edit/7su3Etr1JNYEz324CMy7?p=preview tryng to achieve what i want, but i can't get it to work. I tried with ng-repeat and ng-select, with no luck. Another try i did (in this example) is trying to set the ng-selected property.
This is a part of my html
<body ng-controller="MySampleController">
<select name="repeatSelect" id="repeatSelect" ng-model="SelectedStatus" ng-init="SelectedStatus">
<option ng-repeat="option in StatusList[0]" value="{{option.key}}" ng-selected="{{option.key==SelectedStatus}}">{{option.name}}</option>
</select>
<select name="repeatSelect" id="repeatSelect" ng-model="SelectedOrigin">
<option ng-repeat="option in OriginList[0]" value="{{option.key}}" ng-selected="{{option.key == SelectedOrigin}}">{{option.key}} - {{option.name}}</option>
</select>
<pre>Selected Value For Status: {{SelectedStatus}}</pre>
<pre>{{StatusList[0]}}</pre>
<pre>Selected Value For Origin: {{SelectedOrigin}}</pre>
<pre>{{OriginList[0]}}</pre>
</body>
And this is code from my controller
function MySampleController($scope) {
$scope.StatusList = [];
$scope.OriginList = [];
$scope.ServiceCall = {};
$scope.EntityList = [];
$scope.SelectedStatus = -3;
$scope.SelectedOrigin = 1;
var myList = [
{
item: 'Status',
values: [{ key: -3, name: 'Aperto' },
{ key: -1, name: 'Chiuso' }]
},
{
item: 'Origin',
values: [{ key: 1, name: 'Origin1' },
{ key: 2, name: 'Origin2' },
{ key: 3, name: 'Origin3' }]
}
];
$scope.documentsData = myList;
angular.forEach($scope.documentsData, function (value) {
$scope.EntityList.push(value);
switch ($scope.EntityList[0].item) {
case 'Status':
$scope.StatusList.push($scope.EntityList[0].values);
$scope.EntityList = [];
break;
case 'Origin':
$scope.OriginList.push($scope.EntityList[0].values);
$scope.EntityList = [];
break;
}
});
}
Any help would be appreciated!
Thanks in advance.
You can at least use ng-options instead of ng-repeat + option, in which case the default value works just fine.
<select name="repeatSelect" id="repeatSelect"
ng-options="opt.key as opt.key+'-'+opt.name for opt in StatusList[0]"
ng-model="SelectedStatus"></select>`
You can also make it a bit more readable by specifying the option label as a scope function.
HTML: ng-options="opt.key as getOptionLabel(opt) for opt in StatusList[0]"
Controller:
$scope.getOptionLabel = function(option) {
return option.key + " - " + option.name;
}
Plunker: http://plnkr.co/edit/7BcAuzX5JV7lCQh772oo?p=preview
Value of a select directive used without ngOptions is always a string.
Set as following and it would work
$scope.SelectedStatus = '-3';
$scope.SelectedOrigin = '1';
Read answer here in details ng-selected does not work with ng-repeat to set default value

knockout.js dependent variable selects

[ Please see updates at the bottom ]
I'm trying to make knockout depended selects, it's intended to make a "product" selection by these attributes, for example a product can have "size" and "material", if I selected "size", a knockout script make a request to the backend and retrieves which "material" available for the selected size, in other words, if an attribute is selected, other attributes are filtered out to show only available values ("all sizes": 1,2,3,4,5; "aluminium": 1,4).
Attributes list are completely dynamic, there are about 80 attributes which can be linked to the products in arbitrary way.
Are there any "best practices" for this situation?
I am trying to solve it with code like this, without success yet:
var ViewModel = function(data) {
var self = this;
self.data = data;
self.attributes = ko.observableArray();
self.data.forEach(function(item, i, a) {
// I passed .self to catch it later
// in products as view_model.attributes().
self.attributes.push(new VariableProduct(item, self));
})
};
var VariableProduct = function(item, view_model) {
var self = this;
self.attribute_name = ko.observable(item.name);
self.attribute_value = ko.observable('--');
// list of attribute values
self.attribute_values = ko.computed(function() {
var result = {};
view_model.attributes().forEach(function(attribute, i, a) {
// here I try to filter each attributes lists by values
// it doesn't work well
if (attribute.attribute_name() != self.attribute_name() && self.attribute_value() != '--') {
result = attribute.attribute_values().filter(
function(value) {
return value.indexOf(self.attribute_value()) >= 0;
});
}
});
return result;
});
};
UPDATE 1:
With Dnyanesh's reference to ko.subscribe(), i've achived these results, isn't ok yet, but a progress:
http://jsfiddle.net/xwild/65eq14p3/
UPDATE 2:
At the end it was solved with knockout.reactor and knockout.mapping plugins.
Related stackoverflow question with details and the answer.
For dependent select I think you can use subscribe in following manner
var vm = {
sizes: ko.observableArray([
{ name: 'size 1', id: 1},
{ name: 'size 2', id: 2},
{ name: 'size 3', id: 3},
{ name: 'size 4', id: 4}
]),
selectedSize : ko.observable(0),
};
vm.selectedSize.subscribe(function(newValue){
alert('Selected Size is ---> ' + newValue )
// Here at this point call your ajax or backend method and bind the values which are coming form
});
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<select data-bind="
options: sizes,
optionsText: 'name',
optionsValue: 'id',
value: selectedSize,
optionsCaption: 'Choose Size...'"">
</select>
<select data-bind="
options: material,
optionsText: 'name',
optionsValue: 'id',
value: selectedMaterial,
optionsCaption: 'Choose Material...'"">
</select>
I know I am talking about only part of solution to your problem but, I think you need to divide your data object to bind it to various controls.

knockout object value changes but ui remains the same

I have a drop down list that is bound to a SelectedFormat value. The lists options are populated from external source on load and matches the view models data.Format object base on id.
Take a look at the js fiddle
Can anyone tell me why the model updates but the UI is not updating with the correct Format.Name
Thanks.
HTML:
<div data-bind="text:data.Format.Name"></div>
<select data-bind="
options:Controls,
optionsText: 'Name',
value: data.SelectedFormat"></select>
Model:
var jsonData = {
Id: "abc-123",
Name: "Chicken Cheese",
Format: {
Id: 2,
Name: 'Medium',
Other: 'Bar'
}
};
var self = this;
self = ko.mapping.fromJS(data);
self.SelectedFormat = ko.observable(
//return the first match based on id
$.grep(vm.Controls,function(item){
return item.Id === self.Format.Id();
})[0]
);
//when changed update the actual object that will be sent back to server
self.SelectedFormat.subscribe(function (d) {
this.Format = d;
},self);
In your code, you have Format and SelectedFormat. The former isn't an observable and so can't trigger updates. You have to use SelectedFormat instead.
<div data-bind="text:data.SelectedFormat().Name"></div>
Example: http://jsfiddle.net/QrvJN/9/

Categories

Resources