How to pre-select an option in a dropdown knockout js - data-binding

I've looked at this other question, but can't get my select box to work correctly:
Binding initial/default value of dropdown (select) list
I've got the following Game object:
function Game(visitingTeamDetails, homeTeamDetails, game) {
if (arguments.length > 0) {
this.VisitingTeamDetails = visitingTeamDetails;
this.HomeTeamDetails = homeTeamDetails;
this.GameId = ko.observable(game.GameId);
this.HomeTeamName = ko.observable(game.HomeTeamName);
this.VisitingTeamName = ko.observable(game.VisitingTeamName);
this.SportTypeName = ko.observable(game.SportTypeName);
this.HomeAccountName = ko.observable(game.HomeAccountName);
this.VisitingAccountName = ko.observable(game.VisitingAccountName);
this.GameDateString = ko.observable(game.GameDateString);
this.GameTimeString = ko.observable(game.GameTimeString);
this.AvailableSportTypes = ko.observableArray(game.Sports);
this.sportTypeFunction = function () {
for (sportType in this.AvailableSportTypes()) {
if (this.AvailableSportTypes()[sportType].Name == this.SportTypeName()) {
return this.AvailableSportTypes()[sportType];
}
}
return null;
};
this.SportType = ko.observable(game.SportType);
}
}
SportType is an object with Name and SportTypeId.
I have the following template:
<td rowspan="3"><select data-bind="options: AvailableSportTypes, value: SportType, optionsText:'Name', optionsCaption: 'Choose...'" class="sportType"></select></td>
AvailableSportTypes is a list of SportType.
The list is coming in with the names of the SportTypes in the drop down list, but I can't make the initial selection be SportType. I wrote sportTypeFunction to show myself that the data was coming in correctly, and it would select the correct value, but changing my selection in the drop down would not update SportType.
I'm sure I'm doing something wrong. Anyone see it?
Thanks

When game.SportType gets passed in, it needs to be a reference to the an item in the game.AvailableSportTypes and not just an object that looks the same.
Basically two objects are not equal unless they are actually a reference to the same object.
var a = { name: "test" },
b = { name: "test" };
alert(a === b); //false
So, you would need to call your function to locate the correct object in the array and set it as the value of your observable.
Not that it is way better, but in KO 1.3 you can extend .fn of observables, observableArrays, and dependentObservables to add additional functionality.
Here is a sample: http://jsfiddle.net/rniemeyer/ZP79w

Related

I try to fetch data from firbase but I get this error.The method '[]' can't be unconditionally invoked because the receiver can be 'null'

'''
QuestionModel getQuestionModelFromDatasnapshot(
DocumentSnapshot questionSnapshot) {
QuestionModel questionModel = new QuestionModel();
questionModel.question = questionSnapshot.data()'question'];
List<String> options = [
questionSnapshot.data()["option1"],
questionSnapshot.data()["option2"],
questionSnapshot.data()["option3"],
questionSnapshot.data()["option4"]
];
options.shuffle();
questionModel.option1 = options[0];
questionModel.option2 = options[1];
questionModel.option3 = options[2];
questionModel.option4 = options[3];
questionModel.correctOption = questionSnapshot.data()["option1"];
questionModel.answered = false;
print(questionModel.correctOption.toLowerCase());
return questionModel;
}
'''
It looks like you're using dart with null safety on and you are accessing a list or map that might be null. It's hard to tell from your code, but I'm guessing the offending line is
questionModel.correctOption = questionSnapshot.data()["option1"];
It might be one of the other [] calls earlier in your code (such as
questionSnapshot.data()["option1"]), but the solution is the same.
The problem is that questionSnapshot.data() might return null, and the compiler is flagging it.
If you are sure the data is not null, you can use the ! operator, like this:
questionModel.correctOption = questionSnapshot.data()!["option1"];
Another solution is a conditional null-safe operator ?, with a default value. In this case, the code would look like this:
questionModel.correctOption = questionSnapshot.data()?["option1"]??"DefaultValue;
But I would recommend checking if the returned data is null. It's easier for others to read and can be logged more easily:
var data = questionSnapshot.data();
if (data != null) {
questionModel.correctOption = data["option1"];
}
else {
//do something in that case
}

Very simple if else check in Google App Maker

This is likely embarrassingly easy but I'm new and I've been beating my head against the wall on this for a while now. What I am attempting to do is basically a modified version of the "Hello App Maker!" If else test.
The necessary info I have the following widgets attached to the appropriate data sources:
Dropdown widget called source_name (string - list)
Label widget I've called name (string)
Text Box widget called qty_duration (number)
Label widget I've called hours (number)
I have a dropdown widget called source_name with 5 options. On selection I have the value appear in a label widget I've called name. If the option selected from the drop down widget is ever LABOUR I am trying to then have the value of a Text Box widget called qty_duration appear in a label widget I've called hours
On the source_name dropdown event - onValueChange I have the following code:
// Define variables for the input and output widgets
var nameWidget = app.pages.Apex_job_details.descendants.name;
var outputWidget = app.pages.Apex_job_details.descendants.hours;
var techhours = app.pages.Apex_job_details.descendants.qty_duration;
var nothing = 0;
// If a name is LABOUR, add the qty to the output widget Else output 0.
if (nameWidget == 'LABOUR') {
outputWidget.text = techhours;
} else {
outputWidget = nothing;
}
It's not giving me any errors, but it's also not outputting to the hours label. If I edit the code as follows just to muck with it:
// Define variables for the input and output widgets
var nameWidget = app.pages.Apex_job_details.descendants.name;
var outputWidget = app.pages.Apex_job_details.descendants.hours;
var techhours = app.pages.Apex_job_details.descendants.qty_duration;
var nothing = 0;
// If a name is LABOUR, add the qty to the output widget Else output 0.
if (nameWidget == 'LABOUR') {
outputWidget.text = techhours;
} else {
outputWidget.text = nothing;
}
I'm not sure what I'm doing wrong.
Assuming all labels and input widgets are inside a table row you will want to adjust your code as follows:
var tablerow = widget.parent;
var nameWidget = tablerow.descendants.name.text;
var outputWidget = tablerow.descendants.hours;
var techhours = tablerow.descendants.qty_duration.value;
if(nameWidget === 'LABOUR') {
outputWidget.text = techhours;
} else {
outputWidget.text = null;
}
By using widget.parent in the onValueChange event of the dropdown you will automatically reference the table row and then by using descendants you are referencing only the descendants of that table row. This will bridge the error by using an absolute reference when using table rows. If it still doesn't work let me know.

Maximo Anywhere - Lookup Filter issue

I am working on Maximo Anywhere 7.5.2 (Work Execution app). I need to filter the lookup values based on some conditions within Anywhere.
Ex: Lets consider, I have textfield which can have A or B value only, If it is A from Maximo, then the lookup field should show (P,Q,R,S) and if it is B, Lookup should show (P,Q) only.
This is trickier than you think, because you'll need to write your own code to execute to filter the subsequent lookup. For an example you can look at this code in WODetailHandler.filterAssetForLookup method.
filterAssetForLookup: function(eventContext){
var additionalasset = CommonHandler._getAdditionalResource(eventContext,'additionalasset');
additionalasset._lookupFilter = null;
//save the current asset so we can reset it if the user has to revert the value
var workOrderSet = CommonHandler._getAdditionalResource(eventContext,"workOrder");
if(workOrderSet.getCurrentRecord() != null){
this.curAsset = workOrderSet.getCurrentRecord().get("asset");
this.curAssetDesc = workOrderSet.getCurrentRecord().get("assetdesc");
this.curAssetld = workOrderSet.getCurrentRecord().get("assetld");
}
var siteid = CommonHandler._getWorkorderSiteId(eventContext);
if(siteid == null){
siteid = UserManager.getInfo("defsite");
}
var filter = [];
filter.push({siteid: siteid});
additionalasset.lookupFilter = filter;
},
Then you attach this filter in the filterMethod in the app.xml.
<lookup filterClass="application.handlers.WODetailHandler" filterMethod="filterAssetForLookup" id="WorkExecution.AssetLookup" label="Select Asset" resource="additionalasset">

$.grep on JSON data in multiple array.fields using wildcards?

First off I have looked through similar looking questions but have not found the exact problem asked or answered, so here goes :
I have a JSON Object which consists of about 900+ posts. Looking like this:
var JsonData = [{"rowNumber":563663,"hasWarning":true,"isInvoiceAccount":true,"phone":"","name":"Romerike AS","address1":"Co/Skanning","address2":"PB 52","attention":"","mobile":"","email":"fakt#bos.no","fax":"","zipCity":"N-1471 Askim","invoiceAccount":"","notes":null,"account":"3","country":"NORGE","salesRep":"4","countryCode":"no"},{"rowNumber":563674,"hasWarning":false,"isInvoiceAccount":true,"phone":"","name":"LILLEHAMMER","address1":"POSTBOKS 110","address2":"","attention":"","mobile":"","email":"","fax":"","zipCity":"N-2605 LILLEHAMMER","invoiceAccount":"","notes":null,"account":"14","country":"NORGE","salesRep":"4","countryCode":"no"},{"rowNumber":563676,"hasWarning":true,"isInvoiceAccount":true,"phone":"63929788","name":"Askim Bil AS","address1":"Postboks 82","address2":"","attention":"","mobile":"","email":"karosseri#nyg.no","fax":"","zipCity":"N-2051 Askim","invoiceAccount":"","notes":null,"account":"16","country":"NORGE","salesRep":"4","countryCode":"no"},{"rowNumber":563686,"hasWarning":false,"isInvoiceAccount":true,"phone":"69826060","name":"KAROSSERI A/S","address1":"POSTBOKS 165","address2":"","attention":"","mobile":"","email":"tkar#online.no","fax":"","zipCity":"N-1860 TRØGSTAD","invoiceAccount":"","notes":null,"account":"26","country":"NORGE","salesRep":"4","countryCode":"no"},{"rowNumber":563690,"hasWarning":false,"isInvoiceAccount":true,"phone":"","name":"AUTOSERVICE A/S","address1":"POSTBOKS 15","address2":"","attention":"","mobile":"","email":"","fax":"","zipCity":"N-2851 LENA","invoiceAccount":"","notes":null,"account":"30","country":"NORGE","salesRep":"4","countryCode":"no"},{"rowNumber":563691,"hasWarning":false,"isInvoiceAccount":false,"phone":"","name":"ØYHUS A/S","address1":"POSTBOKS 321","address2":"","attention":"John Doe","mobile":"","email":"","fax":"","zipCity":"N-2817 GJØVIK","invoiceAccount":"","notes":null,"account":"31","country":"NORGE","salesRep":"4","countryCode":"no"}];
I want to filter these data before I read them into a table using $.grep.
The JSON data have been loaded as an object.
In the HTML page I have a textfield named "filter".
The following code works, but only when I search for an exact match:
var JsonFiltered = $.grep(JsonData, function (element, index) {
return element.zipCity == $('#filter').val();
});
$.each( JsonFiltered, function ( index, value ) {
// sorting through the array adding values to a table
[...]
});
Problem 1:
I want to use Wildcards when filtering.
I read something about using regexp but I haven't found any viable examples.
Problem 2:
I want to be able to filter more than one column.
Example: filtering the word "Askim" in both element.name and element.zipCity
So I figured out the solutions myself...
Using Wildcards:
var search_term = $('#filter').val();
var search = new RegExp(search_term, "i");
var JsonFiltered = $.grep(JsonTest, function (element, index) {
var zipC = search.test(element.zipCity)
var names = search.test(element.name)
return zipC + names ;
The solution was to use "new RegExp" with the filter "i" setting.
then I took two search.tests combined them in the return command and... presto
Hope this helps anyone else.

JqxWidgets: Export nested grid

While working with JqxWidges I met a problem with exporting nested grids which use one JSON as a source file. The common solution doesn't work. Actually it exports only parent grid colums.
$("#excelExport").click(function () {
$("#jqxGrid").jqxGrid('exportdata', 'csv', chartName + ' ' + date);
});
One of the existing solutions (http://www.jqwidgets.com/community/reply/reply-to-export-data-from-a-nested-grid-13/) propose to push nested rows into data array while calling initrowdetails function.
Yes it works! But only for nested grids and in case when this grid was selected.
So, from this step I am moving to next aproach:
To collect all necessary data into array using initial JSON (prevent you from gathering only separate selected data);
To initialise parent grid columns with all existing data and mark nested columns as hidden. Then when export don't forget to add true parameter to export both non/hidden columns;
Use standard export with custom array parameter;
That's it!
Data collecting:
var toExport = data.allClientsCountChart;
var exp = new Array();
for(var i in toExport){
var client = {};
var countr = toExport[i].countries;
client[labels.clientType]=toExport[i].clientType;
client[labels.clientTypeCount]=toExport[i].clientTypeCount;
exp.push(client);
for(var j in countr) {
var country = {}
var detailes = countr[j].clientDetails;
country[labels.countryType]=countr[j].countryType;
country[labels.clientsNumber]=countr[j].clientsNumber;
exp.push(country);
for(var d in detailes) {
var det = {}
det[labels.scriptName]=detailes[d].scriptName;
det[labels.clientsCount]=detailes[d].clientsCount;
exp.push(det);
}
}
}
Export:
$("#excelExport").click(function () {
$("#jqxGrid").jqxGrid('exportdata', 'csv', chartName + ' ' + date, true, exp, true);
}
And don't forget to set the fifth pafameter into true to export hidden columns.
No doubds, it looks hardcoded. But it works for me.
So, if you have a good solution - please leave a comment!!!

Resources