Populate dropdownlist in mvc using JQuery onChange - javascript

Have two dropdown lists created in MVC. I want to repopulate the second dropdown list when a user selects something in the first dropdown list.
On page load I am populating the second dropdown list like this:
// Finds selected value
var selectedItem = departureRouteSelectList.First().Value.Substring(2, 2);
// Create new selectList for returnRoute
var returnRouteSelectList = Model.RoutesListConversely
.Where(x => x.Value.StartsWith(selectedItem))
.Select(x => new SelectListItem() { Text = x.Text, Value = x.Value });
The first line finds the last two letters which I use to compare on the Model.RoutesListConversely. The second line creates the list returnRouteSelectList based on what it finds using the two letters.
Can this be done using an onChange() method in JavaScript? So when you select something, this method runs and repopulate the second dropdown list?
Code:
<p>
#Html.Label("Departure route:")
#Html.DropDownListFor(m => m.Departureroute, departureRouteSelectList,
new { #class = "dropdownlist", #id = "departureroute" })
</p>
<p>
#Html.Label("Return route:")
#Html.DropDownListFor(m => m.Returnroute, returnRouteSelectList,
new { #class = "dropdownlist", #id = "returnroute" })
</p>
UPDATE:
Have tried solve this using this code.. .but the problem is that it does not append data, but the clear function is working.
// Getting value from departure dropdown
$("#departureroute").change(function () {
}).change(populateList);
function populateList() {
// Clear dropdown for return route
$("#returnroute").empty();
// Gets last two letters.
var word = (this.value).substring(2);
// Gets the value from the departure route
var selectedId = $("#departureroute").selectedItem.value;
var returnlist = $("#returnroute");
$("#departureroute").each()
{
if (word == selectedId.substring(2)) {
returnlist.append("#departureroute")
}
}
}

I managed to solve my problem using jquery each() function and append.
The following code did the trick:
// On change departure route dropdown list
$("#departureroute").change(function () {
}).change(populateReturnlist);
function populateReturnlist() {
// Clear dropdown for return route
$("#returnroute").empty();
// Gets last two letters.
var word = (this.value).substring(2);
var returnlist = $("#returnroute");
$("#departureroute option").each(function () {
// Gets the value from the departure route
var selectedId = this.value.substring(0, 2);
// Checks so the right routes gets added to list
if (selectedId === word) {
returnlist.append("<option>" + this.text + "</option>")
}
});
};

Related

Angular: Tabkey Press not Populating fields

I'm new to Angular, I have a component which contains some basic fields and dropdown menu.When I select anything from dropdown using tab key the other related field are not getting populated,But it works with mouse click.
receipt-creation.component.ts
populateItems(event: any, obj) {
this.receiptForm.valueChanges.subscribe(() => {
const dirty = this.isFormDirty(this.receiptForm);
if (dirty) {
this.unsavedChanges = true;
}
});
this.receiptLineItems = obj.itemList; // obj.itemList contain the values related to selected item
this.changeDetectorRef.detectChanges();
this.updateSubtotal(); // this function caluclate the total based on the item selected from the dropdown
}
receipt-creation.component.html
<add-new-row
[addNewText]="INVOICE_CONSTS.ADD_LINE_ITEM"
[canAutoAddNewRow]="false"
[checkPristine]="true"
[type]="'receipt'"
[data]="lineItemsMetaData"
[form]="receiptCreationForm"
[triggerExtraAddNewKey]="true"
[itemList]="receiptLineItems"
(changeItemEvent)="populateItems($event, receiptCreationForm)"
(keydown.enter)="preventFormSubmission($event)"
></add-new-row>
With event.preventDefault() the fields gets populated, but I want the default behaviour of tab key to be working.

setValue not workin on dependant Earth Engine ui.Select widget

I am working on an Earth Engine application where I have 2 widgets of type ui.Select that are dependent on each other (bidirectionally dependent). That is, when I make a change in one of them, it changes the list in the other and vice versa.
The behavor is correct, except that when I want to reselect the option that was before the change, it does not work. Due to the items generator script that populate the widgets is allways sure that the previous selection is in the new (modified) items list.
Here are the two widgets implementations
var select_date_init = ui.Select({
items: Object.keys(dates_init),
onChange:function(key) {
var selected_end = select_date_end.getValue();
var selected_init_end_date = dates_init[key][1];
var new_list = Object.keys(get_dates_list(selected_init_end_date,''));
select_date_end.items().reset(new_list);
//select_date_end.items = new_list
if(selected_end !== null){
select_date_end.setValue(selected_end,false)
}else{
select_date_end.setValue(null,false)
}
},
placeholder: 'Seleccionar semestre 1...'
});
var select_date_end = ui.Select({
items: Object.keys(dates_end),
onChange: function(key) {
var selected_init = select_date_init.getValue();
var selected_end_init_date = dates_init[key][0];
var new_list = Object.keys(get_dates_list(system_date_init,selected_end_init_date));
select_date_init.items().reset(new_list);
//select_date_init.items = new_list;
if(selected_init !== null){
select_date_init.setValue(selected_init,false)
}else{
select_date_init.setValue(null,false)
}
},
placeholder: 'Seleccionar semestre 2...'
});
The problem seems to be on the setValue() part of the script. The items of the two widgets are correctly changed, but it allways show the 'Seleccionar semestre 1...' or 'Seleccionar semestre 2...' default text after the change action.
The action I need is:
First step:
Select from 1 -> this changes the list on 2 (originally empty so no pre-selection needed)
Second step:
Select from 2 -> this changes the list on 1 (but keep the selected option in 1)
If the user wants:
Change selection from 1 (or 2) -> update the other list -> keep pre-selected options
Here is the link to the full working script https://code.earthengine.google.com/b251b24ffbc37775e4e5eede8dcbd11f
The onChange function of your button #2 is resetting your button #1 every time. You only need to uncomment lines 209-216 of your code, so the onChange function of your variable var select_date_end looks like this:
var select_date_end = ui.Select({
items: Object.keys(dates_end),
onChange: function(key) {
var selected_init = select_date_init.getValue();
var selected_end_init_date = dates_init[key][0];
var new_list = Object.keys(get_dates_list(system_date_init,selected_end_init_date));
},
placeholder: 'Seleccionar semestre 2...'
});
See code: https://code.earthengine.google.com/9e2d4f13e9bfa57e1df3673a6d82684e

Kendo Combo box always selecting first item on Tab

I have the following code in my Kendo Combo Box:
.Events(events =>
{
events.Select("carUpdate");
events.DataBound("dropDownBind");
})
My carUpdate js method is then as below:
function carUpdate(e) {
debugger;
var rowData = getRowData(e, this);
//If enough data is given to identify unique technology autocomplete the row
var grid = $grid.data('kendoGrid');
if (isUniqueManufacturerDataProvided(rowData)) {
rowData.CarName = this.dataItem(e.selectedIndex).Name;
rowData.CarId = this.dataItem(e.selectedIndex).Id;
return;
}
if (this.selectedIndex === null || this.selectedIndex === -1
|| e.sender._last === kendo.keys.TAB) {
rowData.CarName = pleaseSelect;
rowData.CarId = null;
//$("#Car").data("kendoComboBox").value(pleaseSelect);
//$("#Car").data("kendoComboBox").trigger("close");
return;
} else {
rowData.CarName = this.dataItem(e.selectedIndex).Name;
rowData.CarId = this.dataItem(e.selectedIndex).Id;
}
}
If my ComboBox Contains AB, ABC, ABCD, ABCDE
If I enter A and press the Tab Key I want the combo box to revert to my Please Select Option and move to the next Field in the grid. However what I am finding is the if I just Enter A and press Tab the AB option is getting selected in the box. The other behaviour I want is that ABCDE is entered (i.e - enough data so the combox is filtered to only 1 option) and the Tab key is pressed this option is selected and the cursor moves to the next field in the grid. Is there something I have missed in my js to make this work

angularJs - how to get filtered array

I have a mover directive with the following html for the list
<select class="select-list" multiple
ng-model="unassigned"
name="unAssignedList"
data-no-dirty-check
ng-options="unassignedItem.descrip for unassignedItem in unassignedItems | orderBy:'descrip' | filter: filterCriteria"></select>
So, when I use this directive I can specify my filter-criteria like this
<data-sm:duallist-directive ng-required="false" keep-pristine="true"
unassigned-items-title="'#String.Format(Labels.availableX, Labels.items)'"
unassigned-items="currentItemGroup.unassignedItems"
assigned-items-title="'#String.Format(Labels.assignedX, Labels.items)'"
assigned-items="currentItemGroup.assignedItems"
sortable="false"
filter-criteria="{categoryId:selectedCategoryId}"
selected-item="currentItemGroup.selectedItem">
</data-sm:duallist-directive>
The problem is with the MoveAllLeft (or MoveAllRight) buttons. They have the following code:
$scope.moveRightAll = function() {
var unassignedItems = $scope.unassignedItems.slice(0);
var smItems = $scope.unassignedItems.slice(0);
angular.forEach(smItems, function (value, key) {
$scope.assignedItems.push(value);
removeItem(unassignedItems, value);
});
$scope.unassignedItems = unassignedItems;
if (!$scope.keepPristine)
$scope.form.$setDirty();
$scope.assigned = null;
};
The problem is that it works against original unfiltered array. Say, if I have 642 items in total and I filtered them by category to only, say, 5, I only want to move these 5 items when I press my button, not all 642 which I don't even see on the screen.
How can I modify my code to get only items which are filtered? Also, I don't have to enter filter-criteria, so it should work correctly when nothing is entered in the filter-criteria.
I solved the problem - it turned out to be very easy. I added the following code at the top
var filteredData ;
if ($scope.filterCriteria)
filteredData = $filter('filter')($scope.unassignedItems, $scope.filterCriteria);
else
filteredData = $scope.unassignedItems;
var unassignedItems = filteredData.slice(0);
var smItems = filteredData.slice(0);
and now only filtered items are moved.

How do I clear / reset a Kendo DropDownList with only javascript?

I have a Kendo DropDownList (name=Function) that contains 3 options. When one option is selected, it triggers an ajax call to get data to populate a different DropDownList (name=Parents). This works as-expected. However, if the user then changes the original DropDownList "Function" back to a different selection, I need to clear/reset (remove all options) and disable the "Parents" DropDownList.
function LoadKendoDropdownContents(dropdownBoxId, data) {
var dropdownBox = $("#" + dropdownBoxId).data("kendoDropDownList");
if (data === "" || data === null || $.isEmptyObject(data)) {
var dataSource = [];
}
else {
var dataSource = data;
}
dropdownBox.setDataSource(dataSource);
}
It's really the "var dataSource = []" that is giving me problems. It's like the "Parents" DropDownList isn't refreshing/rebinding when that is applied. All of the options except the one that was selected get removed, but how do I remove the one that was previously selected? I want it to be "empty" again.
Thank you.
---- Solution I used ----
function LoadKendoDropdownContents(dropdownBoxId, data) {
var dropdownBox = $("#" + dropdownBoxId).data("kendoDropDownList");
if (data === "" || data === null || $.isEmptyObject(data)) {
var dataSource = new kendo.data.DataSource({
data: []
});
dropdownBox.text(" --- ");
dropdownBox.value(-1);
}
else {
var dataSource = new kendo.data.DataSource({
data: data
});
dropdownBox.text("[Select]");
dropdownBox.value(-1);
}
dropdownBox.setDataSource(dataSource);
}
It might be easier to use the cascading dropdown feature.
When you change the dataSource, it removes the dropdown items, but you also need to clear the selected text and disable the box, by calling:
dropdownBox.setDataSource(dataSource);
dropdownBox.text('');
dropdownBox.enable(false);
If you have defined a data source for both the parent and child drop down then you could use the cascadeFrom('parent') method in the child and set a value that you can identify as null or clear.

Categories