https://phpout.com/wp-content/uploads/2024/03/4PpsO.png
This is very unique requirement that I want to make up/down (sort order row) functionality. I can able to do up/down using jQuery but I have required complicated requirement which I tried but can’t able to do it. As I attached snapshot. If I click down button #trMain-1989 then that row with next 4 row move after #trMain-1991
Same thing if I click up button of #trMain-1995 then it will move all 5 rows(#trMain-1995, #trLang-1995, #trQuestion-1995, #trAnswer-1995 and #trAct-1995) move to up before #trMain-1993
Here are my codes which I am trying last 3-4 days but not success.
Code: 1
$(document).on('click','.fas', function(event){
var $element = this;
var row = $($element).parents("tr:first");
let index = oTable.row(row).index();
console.log(index);
if($(this).is('.up')){
row.eq(index-4).insertBefore(row.prev());
}else{
row.eq(index+4).insertAfter(row.next());
}
return false;
});
Code: 2
$(document).on('click','.fas', function(event){
if(oTable){
let tr = $(this).closest('tr');
let cls = $(tr).attr("class");
//console.log(cls);
cls = cls.split("-");
//console.log(cls[1]);
let index = oTable.row(tr).index();
let indexes = oTable.rows()[0];
let order = -1;
let buttonName = event.currentTarget.className;
if(buttonName.indexOf('down') > 0){
order = 1;
}
let data1 = oTable.row(index).data();
console.log(data1);
let base_index = indexes.indexOf(index) + order;
console.log(base_index);
let index2 = indexes[base_index];
console.log(index2);
var data2 = oTable.row(index2).data();
//console.log(data1);
oTable.row(index).data(data2);
oTable.row(index2).data(data1);
});
I am expecting that if anyone can help me to correct my code or give any smart solution if it then it would be great for me. Thanks
2
Answers
You want to move them as if they were groups.
Each group start with a
tr
that has class that starts withtrMain-
and ends with atr
that has class that starts withtrAct-
.In order to move up from
tr_current
we find the previoustrMain-
and call ittr_target
. We start moving ourtr_current
and all its next siblings to before thetr_target
untiltr_current
points to the nexttrMain-
which we won’t move.In order to move down, it’s the same logic only a little more advanced since we move like 10 elements below rather than 5 above. Look at code.
Since there is already an answer for your current schema, I’ll suggest some improvements.
Pre-fixing your class names with
tr
is redundant when the element name is alsotr
. This expands totr.trMain-1999
which could be reduced totr.main-1999
without loosing any information.Your class names appear to post-fixed with a year, and since we want to group by this data, you could store this as a
data-
property instead of a class.