Skip to main content
smithcgl9043167
Inspiring
June 30, 2022
Answered

Moving list item to index 0

  • June 30, 2022
  • 1 reply
  • 688 views

Hello everyone, how do I move the selected item to "index 0" in the list?

 

var w = new Window ("dialog", "Rearrange");
var list = w.add ("listbox", undefined, ["one", "two", "three", "four", "five"]);
list.selection = 1;
var up = w.add ("button", undefined, "Index 0");

up.onClick = function () {
 var n = list.selection.index;
 if (n > 0) {
 swap (list.items [n-1], list.items [n]);
 list.selection = n-1;
 }
}

function swap (x, y) {
 var temp = x.text;
 x.text = y.text;
 y.text = temp;
}
w.show ();

 

This topic has been closed for replies.
Correct answer jazz-y
var w = new Window ("dialog", "Rearrange");
var list = w.add ("listbox", undefined, ["one", "two", "three", "four", "five"]);
list.selection = 1;
var up = w.add ("button", undefined, "Index 0");

up.onClick = function () {
 var n = list.selection.index;
 if (n > 0) {
 swap (list.items [0], list.items [n]);
 list.selection = 0;
 }
}

function swap (x, y) {
 var temp = x.text;
 x.text = y.text;
 y.text = temp;
}
w.show ();

1 reply

jazz-yCorrect answer
Legend
June 30, 2022
var w = new Window ("dialog", "Rearrange");
var list = w.add ("listbox", undefined, ["one", "two", "three", "four", "five"]);
list.selection = 1;
var up = w.add ("button", undefined, "Index 0");

up.onClick = function () {
 var n = list.selection.index;
 if (n > 0) {
 swap (list.items [0], list.items [n]);
 list.selection = 0;
 }
}

function swap (x, y) {
 var temp = x.text;
 x.text = y.text;
 y.text = temp;
}
w.show ();
smithcgl9043167
Inspiring
June 30, 2022

Perfect! Thanks for solving my problem. @jazz-y  taking advantage of this topic here, I took the opportunity to ask you, how would I move any item to the final index of the list?.

Legend
June 30, 2022
var w = new Window ("dialog", "Rearrange");
var list = w.add ("listbox", undefined, ["one", "two", "three", "four", "five"]);
list.selection = 1;
var up = w.add ("button", undefined, "Index 0");

up.onClick = function () {
 var n = list.selection.index;
 if (n >= 0) {
 swap (list.items [n], list.items [list.items.length-1]);
 list.selection = list.items.length-1;
 }
}

function swap (x, y) {
 var temp = x.text;
 x.text = y.text;
 y.text = temp;
}
w.show ();