triplethreat77 triplethreat77 - 2 months ago 9
jQuery Question

Gridster serialize data to 1-5 order (recursive loop)?

I'm using the Gridster plugin, and I need to capture the newly dragged order in an 1-5 manner. I know that we choose row first, then order (column). So, row:1, order:1 would be id: grid_74. The next closest order number greater than 1 in row 1 is 5, so id: grid_78. How can I accomplish this?

1 - grid_74

2 - grid_78
(etc...)

var gridinfo = gridster.serialize()


object

n4p n4p
Answer

I think you might just need a sort.

// Just setting up object array to match example:
var gridinfo = [
  { id: "grid_75", order: 5, row: 4 },
  { id: "grid_74", order: 1, row: 1 },
  { id: "grid_91", order: 9, row: 1 },
  { id: "grid_85", order: 5, row: 7 },
  { id: "grid_78", order: 5, row: 1 }
]


// This sort is what does all the magic.. it first sorts by row, then order.
// I lifted this bit of javascript ninjutsu from: 
// http://www.sitepoint.com/sophisticated-sorting-in-javascript/
gridinfo.sort(function(a, b)
{
  if(a.row === b.row)
  {
    return a.order < b.order ? -1 : a.order > b.order ? 1 : 0;
  }

  return a.row - b.row;
});


// Display sorted array:
for(var k=0; k<gridinfo.length; k++)
{
  document.write('id: '+gridinfo[k].id+'<br>');
  document.write('row: '+gridinfo[k].row+'<br>');
  document.write('order: '+gridinfo[k].order+'<br>');
  document.write('-------<br>');
}

Comments