Get label of selection with digit/registry in JavaScript - javascript

I think I am using digit/registry stuff and I have this select(drop-down list) which when I do JSON.stringify() on it, part of the information it gives is this:
"_optionsMdl" : [
{
"label" : "558Label",
"selected" : false,
"value" : 558
},
{
"label" : "739Label",
"selected" : true,
"value" : 739
},
How do I get the selected label value?
In above example, the "739Label" is selected, and I want some way to get that label value.
This is what I have that gives part of above output:
var cat52 = registry.byId("c52");
console.log("cat52="+JSON.stringify(cat52));
I tried something like:
console.log("cat52.value="+cat52.get("value"));
console.log("cat52.label="+cat52.get("label"));
And it gives the right value, but not the label.
Label is the control's label, not the selected item's label.
I am new to UI coding and don't even really know what to search to get userful info for this, so hopefully this is not a duplicate..

You can use Array.prototype.some():
The some() method tests whether some element in the array passes the test implemented by the provided function.
var object = { "_optionsMdl": [{ "label": "558Label", "selected": false, "value": 558 }, { "label": "739Label", "selected": true, "value": 739 }] },
selectedItem;
object['_optionsMdl'].some(function (a) {
if(a.selected) {
selectedItem = a;
return true;
}
});
document.write('<pre>' + JSON.stringify(selectedItem, 0, 4) + '</pre>');

Related

How to get overall error status on Material UI DataGrid?

I am using Material UI DataGrid component to render EXCEL file. Each Excel file has several column Names and have specific types. For example:
const columns = [
{
"field": "uwgroup",
"headerName": "Group",
"minWidth": 200,
"editable": true
},
{
"field": "Amazing column Name ",
"flex": 1,
"minWidth": 150,
"editable": true
},
{
"field": "Building TSI",
"type": 'number',
"flex": 1,
"minWidth": 150,
"editable": true
},
{
"field": "dev",
"flex": 1,
"minWidth": 150,
"editable": true
}
]
The column Name Building TSI is of type number. And I am adding class name invalid using cellClassName, something like:
classnames({
invalid: !isPositiveNumber(params.value)
})
It works fine and renders class name and indicates error cells. The problem is, I want to count total number of error cells. The reason is, we only allow to save the grid values to the database, if there are no errors in any cells.
Solutions, I have tried so far:
Add state for errorCount and increment errorCount when I add class. This causes several re-renders and exceeds memory limit.
I tried to use document.getElementByClassNames('invalid') and check its length. It works only for the rendered item. That is to say, if excel file has more than 10 rows, it is paginated. The invalid cells count is only done for the currently rendered page.
I tried to use preProcessEditCellProps props to indicate error. However, I could not find anyway to get the total error cells count. Only thing, I could get out of this props is an ability to not allow user to enter incorrect value.
I even tried using localStorage. It has the exact same issue as solution number 2.
I would appreciate if anyone has faced similar scenario. It would be nice to get overall error cells count, so, I can enable to disable SAVE button.
One of the constraints that I have is the excel files are huge and contains on average of 30-40k rows and 25-40 columns. Adding state for each cells becomes less performant.
Thanks in advance!
Having another property in columns and referring to it before exporting for each cell/row can help.
In this example, invoke eligibleForExport function with the columns definiton and the actual data as parameters will give a boolean stating if error exists or not. Can be changed to count errors as well.
const isInvalidBuildingTSI=(value)=>!isPositiveNumber(value);
const isPositiveNumber=(num)=>num>=0;
const eligibleForExport=(columns,data)=>{
return !(data.find(row=>columns.find(column=>row[column.field]
&& typeof column["isValid"] === "function" && column["isValid"](row[column.field]))))
}
const columns = [
{
"field": "uwgroup",
"headerName": "Group",
"minWidth": 200,
"editable": true
},
{
"field": "Building TSI",
"type": 'number',
"flex": 1,
"minWidth": 150,
"editable": true,
"isValid" : isInvalidBuildingTSI,
"cellClassName":isInvalidBuildingTSI(param.value)?"invalid":""
}
];
If the initial data is always valid an easy way to solve your issue would be to follow the DataGrid documentation about clients side validation:
Client-side validation 🔗
To validate the value in the cells, first add a
preProcessEditCellProps callback to the column definition of
the field to validate. Once it is called, validate the value provided
in params.props.value. Then, return a new object contaning
params.props and also the error attribute set to true or false. If
the error attribute is true, the value will never be committed.
const columns: GridColDef[] = [
{
field: 'firstName',
preProcessEditCellProps: (params: GridEditCellPropsChangeParams) => {
const hasError = params.props.value.length < 3;
return { ...params.props, error: hasError };
},
},
];
For your scenario this would result in the following:
const columns = [
{
"field": "uwgroup",
"headerName": "Group",
"minWidth": 200,
"editable": true
},
{
"field": "Amazing column Name ",
"flex": 1,
"minWidth": 150,
"editable": true
},
{
"field": "Building TSI",
"type": 'number',
"flex": 1,
"minWidth": 150,
"editable": true,
preProcessEditCellProps(params) {
const invalid = !isPositiveNumber(params.props.value);
return { ...params.props, error: invalid };
}
},
{
"field": "dev",
"flex": 1,
"minWidth": 150,
"editable": true
}
]
There is an important difference with what you currently have. This validation only effects edits. So the initial data has to be valid. The advantage is that you no longer have to use classnames({ invalid: !isPositiveNumber(params.value) }) and the save button can always be enabled, since all committed changes can be assumed to be valid.
If the initial data can be invalid, this is probably not the answer you're looking for.

Datatable search in nested table

I'm using metronic v5.0.7.1 i have a datatable which is contains nested array so i just want to search in this array.
I'm able to bind my case status like that;
{
field: 'case.case_status',
title: "Status",
}
there is my search field;
var query = datatable.getDataSourceQuery();
$('#m_form_durum').on('change', function () {
datatable.search($(this).val(), 'case.case_status');
}).val(typeof query.case.case_status !== 'undefined' ? query.case.case_status : '');
After that im getting this error "Cannot read property 'case_status' of undefined". How can I specify the nested field in this case?
By the way if I replace my field to 'count' which is in my array instead of 'case.case_status' its work very well. Just nested fields give this error.
Also this is my sample data:
[
{
"id": 93,
"case": {
"id": 99,
"case_status": 1,
},
"user": "1",
"count": "2",
"created_at": "2018-02-08T09:00:00.884590+03:00",
"modified_at": "2018-02-08T09:00:00.884612+03:00",
"is_deleted": false,
}
]

jQuery DataTables default column value

I am trying to include an invisible column in a jQuery DataTable that can be set to default true in place of a null or undefined encountered in the data source.
Say I am working with a 6-columns DataTable. The first 5 columns are visible. The 6th column is set to not be visible. And it must contain either a true or false, regardless of whether the data source object has the corresponding key. In the column definitions for the DataTable, I tried this but it did not work.
{ "defaultContent": true, "data": "existing", "visible": false }
According to the API, I think defaultContent works only when data is null. Maybe that's why it does not work. I have provided the HTML, JS data and JS code for initializing the DataTable. Notice that once the DataTable is loaded and rendered, I dynamically append a row and re-draw. The data for this row contains the 6th column property and that is gets set just fine.
HTML:
<div id="demo">
</div>
JavaScript (data initialization):
var dataSet = [
{'engine':'Webkit','browser':'Safari 1.2','platform':'OSX.3','version':'125.5','grade':'A'},
{'engine':'Other browsers','browser':'All others','platform':'-','version':'-','grade':'U'}
];
JavaScript (DataTable creation and initialization):
$('#demo').html('<table class="display" id="example"></table>');
$('#example').dataTable( {
"data": dataSet,
"columns": [
{ "sortable" : false, "data": null, "defaultContent": "<button>Select</button>", "title" : "Choose"
},
{ "title": "Engine", "data": "engine" },
{ "title": "Browser", "data": "browser" },
{ "title": "Platform", "data": "platform" },
{ "title": "Version", "data": "version", "class": "center" },
{ "title": "Grade", "data": "grade", "class": "center" },
{ "defaultContent": true, "data": "existing", "visible": false }
],
initComplete: function(oSettings, json) {
console.log('drawing complete');
if (oSettings.fnRecordsTotal() > 1) {
$('#example').DataTable().row.add({
'engine' : 'Presto',
'browser' : 'Opera 7.5',
'platform' : 'Win 95+ / OSX.2+',
'version' : '-',
'grade' : 'A',
'existing' : false
}).draw();
}
}
} );
Here is the JSFiddle for the above example. If you click on the Select button in the first two rows, it returns undefined. The Select button on the third row yields false. I want the first two rows' Select button to yield true.
How do I set a default value for the 6th (invisible) column if no key/value is provided in the data-set object?
It returns undefined because existing not exists in dataSet. dataSet is static, defaultContent does not populate its value to the original dataSet. What you really want is the value of the hidden column, which will contain either defaultContent or dynamically added existing values.
var row = $('#example').DataTable().row( $(this).parents('tr') ),
index = row.index(),
data = row.cell(index, 6).data();
alert(data);
will return true, true and false. Forked fiddle -> http://jsfiddle.net/vsx7uxnf/

FormatSelection in select2Option is removing data

FormatSelection in select2Option removing data.
I am receiving my data in
$scope.superclasses = superclassDataList.data;
where superclassDataList is coming from service in angular.
Data i received from service is :
{
"data": [{
"name": "new Test",
"id": 4506898162253824,
"attendanceAllowed": true,
"subclasses": [{
"title": "HIN",
"children": null,
"entityName": "MyClass",
"entityId": 5136918324969472
},
{
"title": "ENG 101 A",
"children": null,
"entityName": "MyClass",
"entityId": 5699868278390784
}]
}
],
"success": true,
"errorMessage": ""
}
Code where i am applying my ng-grid to show this data:
<div ng-show="superclasses[row.rowIndex].edit"><div id="subclasses" ng-model="superclasses[row.rowIndex].subclasses" ui-select2="select2Options" data-placeholder="Add Subclasses" style="width:100%" multiple></div></div>
<div class="ngCellText" ng-class="col.colIndex()" style="display:inline" ng-show="!superclasses[row.rowIndex].edit" ng-repeat="subclass in superclasses[row.rowIndex].subclasses">{{subclass.title}} ,</div>
(I added one extra field "edit" in superclasses so don't be confuse with that. If it's true first div(Editable mode) will be visible else second(View mode))
Code for select2 i write is:
$scope.subclassNameFormat="";
$scope.select2Options = {
allowClear : true,
multiple: true,
width : 550,
minimumInputLength: 3,
query: function (query){
SuperclassService.getSubclassesUnassigned({searchTerm: query.term.toUpperCase()}, function(response) {
$scope.classesList = response.data;
var data = {
results: []
};
$.each($scope.classesList, function(){
if(this.list === undefined || this.list.length === 0) {
data.results.push({id: this.id, text: this.title,isApplied: false});
}
});
query.callback(data);
}, function(error){
console.log("Superclass is not deleted.... Please try again");
});
},
formatSelection: function format(state) {
if((state.title === undefined || state.title === "") && (state.text !== undefined && state.text !== "")){
$scope.subclassNameFormat = state.text;
}else if((state.text === undefined || state.text === "") && (state.title !== undefined && state.title !== "") ){
$scope.subclassNameFormat = state.title;
}
}
};
here getSubclassesUnassigned() method retrieve data from server on the basis of 3 character i entered to search: (minimumInputLength: 3),
Question: The data in $scope.superclasses comes from server is complete(JSON Data written above). And for a moment complete data of subclasses visible(when edit is false) (in this case name of subclasses HIN, ENG 101 A). Once it entered in "formatSelection" part of "$scope.select2Options" one data from "subclasses" array will be remove and it reflect on the "subclasses" column in grid (the code i write above) and show only one name (either "HIN" or "ENG 101 A"). I don't know why it get entered in "formatSelection" part of "select2options" because till data time "edit" field was false. (See in div code ng-show="!superclasses[row.rowIndex].edit" ). I don't know how it reflect the data. and even delete the data completely(2nd object of subclasses array.).
Have a same problem when value of div is in editable mode(ng-show="superclasses[row.rowIndex].edit") it only show one value of subclasses array.
data after passing control from FormatSelection:
{
"data": [{
"name": "new Test",
"id": 4506898162253824,
"attendanceAllowed": true,
"subclasses": [{
"title": "HIN",
"children": null,
"entityName": "MyClass",
"entityId": 5136918324969472
}]
}],
"success": true,
"errorMessage": ""
}
I tried everything from reading complete doc. about query and formatSelection from select2 but didn't find or understand anything, and also search on stackoverflow but didn't find any relevant link or didn't understand from those already on site. I know it might be silly question for some professionals but i started working on angular just 2 days ago.
Ask me in more explanation is required. I will try to provide everything that i know.
Thanks in advance.
PS: Please ignore My grammatical mistakes.
Try this code before "query :" in select2Option
initSelection: function(element, callback) {},
It will initialize your data for select2 which you are receiving in $scope.superclasses. It is working fine for me.

In kendo dataviz chart local data binding , JSON data value was spilted?

I create a Column chart using Kendo ui dataviz.
In my program, i am going to bind the local Javascript Array variable data to chart datasource.
The JSON data was spilted like "3""9""6" for "396".
I dont know why it happened. My Source code is given blow. Please check it and Please give the solution.
Source:
/**************Variable Declaration**********************************/
var eligibilityData = new Array();
eligibilityData = {
mem_status: {
a: 396, b: "56", c: "1125", d: "8423"
}
};
/**************Create Chart**********************************/
function createBarChart(eligibilityData) {
/****** Issue: A value is 396 but it spilted into "3","9","6"************/
$("#Chart1").kendoChart({
theme : $(document).data("kendoSkin") || "default",
dataSource : {
data: JSON.stringify(eligibilityData.mem_status.a),
},
seriesDefaults: { type: "column", },
series : [
{ field: "a", name : "A" }
],
tooltip : { visible: true, },
});
}
Local data should be passed as an array. No need to call JSON.stringify
data: [eligibilityData.mem_status]
See: http://docs.kendoui.com/api/framework/datasource#configuration-data-Array
JSON.stringify does not do what you expect. What you sentence really does is:
It gets the number 396 and converts it to a string.
Converts a string into an array of one character per element.
Not sure about the way you define the DataSource (why you want a DataSource with only one element) but if that is really what you want, you might try:
dataSource : {
data: [eligibilityData.mem_status.a]
},
or
dataSource : {
data: [eligibilityData.mem_status]
},

Categories