This has been troubling me for the passed few hours now.
I have a table. Within that table i'm looking for the closest, previous table row with a specific data attribute. I'm doing this search right after a successful use of jquery sortable. I've tried almost everything and it ALWAYS comes up with the wrong thing.
Here's what i'm using
var newIndex = ui.item.index();
var menuLevel = parseInt($("#menu-table").find("[data-menu-nesting='" + newIndex + "']").attr("data-menu-level"));
var menuId = $("#menu-table").find("[data-menu-nesting='" + newIndex + "']").attr("data-menu-id");
if (menuLevel == 2) {
var findAboveRowName = $(".menu-table-rows[data-menu-nesting='" + newIndex + "']").prev(".menu-table-rows").data("menu-level","1").attr("data-menu-name");
alert(findAboveRowName);
}
if (menuLevel == 3) {
var findAboveRowName = $(".menu-table-rows[data-menu-nesting='" + newIndex + "']").prev(".menu-table-rows").data("menu-level","2").attr("data-menu-name");
alert(findAboveRowName);
}
Essentially, the variable "newIndex" is supposed to grab the new position of the row after being sorted, menuLevel is supposed to grab the data attribute "menu-level" of that table row, and menuId is grabbing another data attribute of that table row.
It's specifically looking for the nearest, previous menu-level attribute in the table rows. So if a table row with a menu-level attribute of 2 is moved, it's looking for the nearest table row with a menu-level attribute of 1.
The full jquery sortable script i'm using if needed
$("#sortable").sortable({
update: function(event, ui) {
var serial = $('#sortable').sortable('serialize');
var newIndex = ui.item.index();
var menuLevel = parseInt($("#menu-table").find("[data-menu-nesting='" + newIndex + "']").attr("data-menu-level"));
var menuId = $("#menu-table").find("[data-menu-nesting='" + newIndex + "']").attr("data-menu-id");
if (menuLevel == 2) {
var findAboveRowName = $(".menu-table-rows[data-menu-nesting='" + newIndex + "']").prev(".menu-table-rows").data("menu-level","1").attr("data-menu-name");
alert(findAboveRowName);
// $.post("./menu-controller.php", { adjustParent: true, id: menuId, parent: findAboveRowName });
}
if (menuLevel == 3) {
var findAboveRowName = $(".menu-table-rows[data-menu-nesting='" + newIndex + "']").prev(".menu-table-rows").data("menu-level","2").attr("data-menu-name");
alert(findAboveRowName);
// $.post("./menu-controller.php", { adjustParent: true, id: menuId, parent: findAboveRowName });
}
$.ajax({
url: "./menu-controller.php",
type: "post",
data: serial,
success: function() {
$("#sortable").load("./menu-manager.php #menu-table", function() {
$.get('./menu-admin.js');
});
},
error: function(){
alert("A problem occurred when moving this menu item. Please try again or contact support.");
}
});
},
handle:'.move-item',
connectWith:'#menu-table',
placeholder: "highlight",
containment: "parent",
revert: true,
tolerance: "pointer",
items: 'tbody > *'
});
JSFIDDLE
See Question&Answers more detail:
os