I have a datatable with day name column. I want to sort this column by day name e.g. if I have [Friday, Monday,Sunday] sorting should return [Monday ,Friday, Sunday] (ascending) and [Sunday,Friday, Monday] (descending).
I tried to use custom sorting but I wasn't able to represent my custom order.
Do you have ideas ?
Thanks
I found a solution for my problem. I created a hidden column with numeric values. The sorting will be based in this column. This is the custom sort function
// Custom function to sort Column by another Column
var mysortFunction = function(a, b, desc) {
// Deal with empty values
if(!YAHOO.lang.isValue(a)) {
return (!YAHOO.lang.isValue(b)) ? 0 : 1;
} else if(!YAHOO.lang.isValue(b)) {
return -1;
}
// compare column values
var comp = YAHOO.util.Sort.compare;
var compState = comp(a.getData("myhiddenColumn"), b.getData("myhiddenColumn"), desc);
return compState;
};
And the column defs :
var myColumnDefs = [
{ key: "A", sortable:true,hidden:true },
{ key: "columnToSort",label:"ABC", sortable:true, sortOptions: { sortFunction: mysortFunction }
{ key: "myhiddenColumn", sortable:true, hidden:true }
}
];
Hope this helps
Related
I have data
{
"id": 1000,
"price": "99,01USA",
},
{
"id": 1001,
"price": "100USA",
},
{
"id": 1002,
"price": "780USA",
},
{
"id": 1003,
"price": "20USA",
},
How I sort order by price (ASC , DESC)
You can alter it a little to parse price to integer and then sort it
You can create a dynamic sort function that sorts objects by their value that you pass:
function dynamicSort(property) {
var sortOrder = 1;
if(property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a,b) {
/* next line works with strings and numbers,
* and you may want to customize it to your needs
*/
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
So you can have an array of objects like this:
var People = [
{Name: "Name", Surname: "Surname"},
{Name:"AAA", Surname:"ZZZ"},
{Name: "Name", Surname: "AAA"}
];
...and it will work when you do:
People.sort(dynamicSort("Name"));
People.sort(dynamicSort("Surname"));
People.sort(dynamicSort("-Surname"));
Actually this already answers the question. Below part is written because many people contacted me, complaining that it doesn't work with multiple parameters.
Multiple Parameters
You can use the function below to generate sort functions with multiple sort parameters.
function dynamicSortMultiple() {
/*
* save the arguments object as it will be overwritten
* note that arguments object is an array-like object
* consisting of the names of the properties to sort by
*/
var props = arguments;
return function (obj1, obj2) {
var i = 0, result = 0, numberOfProperties = props.length;
/* try getting a different result from 0 (equal)
* as long as we have extra properties to compare
*/
while(result === 0 && i < numberOfProperties) {
result = dynamicSort(props[i])(obj1, obj2);
i++;
}
return result;
}
}
Which would enable you to do something like this:
People.sort(dynamicSortMultiple("Name", "-Surname"));
Subclassing Array
For the lucky among us who can use ES6, which allows extending the native objects:
class MyArray extends Array {
sortBy(...args) {
return this.sort(dynamicSortMultiple(...args));
}
}
That would enable this:
MyArray.from(People).sortBy("Name", "-Surname");
I'm a total newbie when it comes to scripts and I honestly don't really use it often at all but I thought it'd be fun to automatize an alphabetical order sorting I wanted to do and so I used this script:
/** Build a menu item
From https://developers.google.com/apps-script/guides/menus#menus_for_add-ons_in_google_docs_or_sheets
**/
function onOpen(e) {
var menu = SpreadsheetApp.getUi().createMenu('Sort');
if (e && e.authMode == ScriptApp.AuthMode.NONE) {
// Add a normal menu item (works in all authorization modes).
menu.addItem('Sort Sheet', 'sort');
} else {
// Add a menu item based on properties (doesn't work in AuthMode.NONE).
var properties = PropertiesService.getDocumentProperties();
var workflowStarted = properties.getProperty('workflowStarted');
if (workflowStarted) {
menu.addItem('Sort Sheet', 'sort');
} else {
menu.addItem('Sort Sheet', 'sort');
}
menu.addToUi();
}
}
function sort() {
/** Variables for customization:
Each column to sort takes two variables:
1) the column index (i.e. column A has a colum index of 1
2) Sort Asecnding -- default is to sort ascending. Set to false to sort descending
**/
//Variable for column to sort first
var sortFirst = 3; //index of column to be sorted by; 1 = column A, 2 = column B, etc.
var sortFirstAsc = true; //Set to false to sort descending
//Variables for column to sort second
var sortSecond = 1;
var sortSecondAsc = true;
//Number of header rows
var headerRows = 1;
/** End Variables for customization**/
/** Begin sorting function **/
var activeSheet = SpreadsheetApp.getActiveSheet();
var sheetName = activeSheet.getSheetName(); //name of sheet to be sorted
var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
var range = sheet.getRange(headerRows+1, 1, sheet.getMaxRows()-headerRows, sheet.getLastColumn());
range.sort([{column: sortFirst, ascending: sortFirstAsc}, {column: sortSecond, ascending: sortSecondAsc}]);
}
It worked very well but I wondered if there was a way to not have it work in two specific tabs of the same sheets?
I believe your goal as follows.
You want to execute the script of sort for the sheets except for the specific sheets.
In this case, how about declaring the excluded sheet names and checking the current sheet using the excluded sheet names? When this is reflected to your script, it becomes as follows.
Modified script:
In this case, please set the sheet names you want to exclude to excludeSheetNames. At sample script, when the active sheet is "Sheet1" and "Sheet2", the script below the if statement is not run.
function sort() {
var excludeSheetNames = ["Sheet1", "Sheet2"]; // <--- Added
var sortFirst = 3;
var sortFirstAsc = true;
var sortSecond = 1;
var sortSecondAsc = true;
var headerRows = 1;
var activeSheet = SpreadsheetApp.getActiveSheet();
var sheetName = activeSheet.getSheetName();
if (excludeSheetNames.includes(sheetName)) return; // <--- Added
var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
var range = sheet.getRange(headerRows + 1, 1, sheet.getMaxRows() - headerRows, sheet.getLastColumn());
range.sort([{ column: sortFirst, ascending: sortFirstAsc }, { column: sortSecond, ascending: sortSecondAsc }]);
}
For example, if you want to run the script below the if statement for only excludeSheetNames, please modify if (excludeSheetNames.includes(sheetName)) return; to if (!excludeSheetNames.includes(sheetName)) return;.
Reference:
includes()
I have found a filter configuration in order to filter empty columns.
The issue is that I only know how to apply this to one column (In the example column number 8).I want to apply this to other columns at the same time (For instance columns 8, 12 and 17).
Thank you!
filter_functions: {
8: {
'{empty}' : function (e, n, f, i, $r, c) {
return $.trim(e) === '';
}
}
},
filter_selectSource: {
8: function (table, column, onlyAvail) {
// get an array of all table cell contents for a table column
var array = $.tablesorter.filter.getOptions(table, column, onlyAvail);
// manipulate the array as desired, then return it
array.push('{empty}');
return array;
}
},
Both the filter_functions and the filter_selectSource options will accept an object key containing a jQuery selector, as well as a zero-based column index. For example, if column headers 8, 12 and 17 all had the class name of "add-empty", then set the options as follows:
filter_functions: {
'.add-empty' : {
'{empty}' : function (e, n, f, i, $r, c) {
return $.trim(e) === '';
}
}
},
filter_selectSource: {
'.add-empty' : function (table, column, onlyAvail) {
// get an array of all table cell contents for a table column
var array = $.tablesorter.filter.getOptions(table, column, onlyAvail);
// manipulate the array as desired, then return it
array.push('{empty}');
return array;
}
}
I'm a newbie in asp.net so I'm hoping you could give me some help on my dropdownlist bound to a table.
Here's the scenario:
I have a table Account with fields UserId, UserName and Type. The Type field contains 3 items: 'S', 'A', and 'U'. Each user has his own Type. I have a dropdownlist named 'ddlType' which is already
bound on the Account table. However, I want the options of the dropdownlist to be displayed as 'Stakeholder', 'Approver', and 'User' instead of displaying letters/initials only. Since I do not prefer making any changes in the database, how can I change those options through code behind?
Here's my code:
public void BindControls(int selectedUserId)
{
DataTable dtAccount = null;
try
{
dtAccount = LogBAL.GetAccountDetails(selectedUserId);
if (dtAccount.Rows.Count > 0)
{
lblUserId.Text = dtAccount.Rows[0]["UserId"].ToString();
txtUserName.Text = dtAccount.Rows[0]["UserName"].ToString();
ddlType.SelectedValue = dtAccount.Rows[0]["Type"].ToString();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
dtAccount.Dispose();
}
}
Any help from you guys will be appreciated. Thanks in advanced! :D
You can bind Dropdownlist in codebehind.
Get your data "Type" into array. Make array two dimentional and assign values to it.
After having data your array will looks like this,
string[,] Types = { { "Stakeholder", "S" }, { "Approver", "A" }, { "User", "U" } };
Now assign values to Dropdown,
int rows = Types.GetUpperBound(0);
int columns = Types.GetUpperBound(1);
ddlType.Items.Clear();
for (int currentRow = 0; currentRow <= rows; currentRow++)
{
ListItem li = new ListItem();
for (int currentColumn = 0; currentColumn <= columns; currentColumn++)
{
if (currentColumn == 0)
{
li.Text = Types[currentRow, currentColumn];
}
else
{
li.Value = Types[currentRow, currentColumn];
}
}
ddlType.Items.Add(li);
}
I haven't tested it but hopefully it will work.
How do I obtain the selected row value for a hidden column in a Telerik RadGridView? The column is hidden on the aspx page and I would like to retrieve the value on the client side (JavaScript).
Essentially, I want to display a name in the grid view and be able to retrieve a value from the hidden field "ID" to bring up an edit form.
Here is an example of how I'm hiding the RadGridView column.
code sample:
onKeyPressEvent(sender, args) {
var variable = function (e) {
e = e || window.event;
if (e.keyCode == 13) {
var PartyID = args.getDataKeyValue("PARTY_ID");
var oManager = '<%=winMgr.ClientID %>';
var oManager = window.radopen("AttorneyEdit.aspx?PARTY_ID=" + PartyID, null);
oManager.setSize(1000, 530);
//Width, Height oManager.center();
} else { return true;
}
}
theForm.onkeypress = variable
}
Thanks for your help...
maybe you're going the wrong way. There is a property called "ClientDataKeyNames" on the mastertableview. You can add several key separated by a comma in this property. Then you'll be able to get your value without adding an extra column.
You should do something like this:
function onKeyPressEvent(sender, args) {
if (args.get_keyCode() == 13) {
var dataItem=sender.get_selectedItems()[0];
var PartyID = dataItem.getDataKeyValue("PARTY_ID");
var oManager = '<%=winMgr.ClientID %>';
var oManager = window.radopen("AttorneyEdit.aspx?PARTY_ID=" + PartyID, null);
oManager.setSize(1000, 530);
//Width, Height oManager.center();
}
else {
return true;
}
}
good luck