Skip navigation.

Csabi's blog

Things about Mandriva, Linux & the rest of the world

Simple Javascript Toolbox

I am new to JavaScript and I had to create a toolbox containing 2 lists with left-right buttons to move elements between them and another 2 buttons to move up/down the elements of the second lists.
The lists are made within the HTML part of the page with the <SELECT multiline> tag.

After searching a lot, I found some tutorials but they were overly too complicated for my level of knowledge of JavaScript.

After some time and disappointment I ended up writing my own code from zero and I thought I will share it with whoever would need it.

Note, this is a very basic and simple example from a beginner in JavaScript. There is most certainly space for improvements.

//Function to move data from left to right and right to left. Parameter direction is "right" or "left"
function moveData(direction){
if(direction=="right"){
var sursa = document.getElementById("statii");
var destinatie = document.getElementById("ruta");
}else{
var destinatie = document.getElementById("statii");
var sursa = document.getElementById("ruta");
}

for(var i = sursa.options.length - 1 ;i >= 0;i--){
if(sursa.options.selected){
destinatie.options[destinatie.options.length] = new Option(sursa.options.text, sursa.options.value, true, true);
sursa.remove(i);
}
}
return false;
}

//Function to move elementr UP or DOWN in a list
function moveUpDown(direction){
var sursa = document.getElementById("ruta");

for(var i = sursa.options.length - 1 ;i >= 0;i--){
if(sursa.options.selected){
var text=sursa.options.text;
var value=sursa.options.value;
sursa.options.selected=false;
if(direction=="up" && i>0){
sursa.options.text=sursa.options[i-1].text;
sursa.options.value=sursa.options[i-1].value;
var selobject=sursa.options[i-1];
sursa.options[i-1].text=text;
sursa.options[i-1].value=value;
}else if(direction=="down" && i< sursa.options.length-1){
sursa.options.text=sursa.options[i+1].text;
sursa.options.value=sursa.options[i+1].value;
sursa.options[i+1].text=text;
sursa.options[i+1].value=value;
var selobject=sursa.options[i+1];
}else{
var selobject=sursa.options;
}
}
}
selobject.selected=true;
return false;

}


//Function to submit all the elements of a list. I made this by selecting all elements from within the submit function
function submitAll(){
var sursa = document.getElementById("ruta");
for(var i = sursa.options.length - 1 ;i >= 0;i--){
sursa.options.selected=true;
}


In my HTML the left list has id="sursa" and the right one has id="ruta". Each button has it's "onClick" set to the appropriate javascript function.

If you need any more explanations, just ask.

Ready for the FutureBlog Action Day

How to use Quote function:

  1. Select some text
  2. Click on the Quote link

Write a comment

Comment
(BBcode and HTML is turned off for anonymous user comments.)

If you can't read the words, press the small reload icon.


Smilies