I have always used this code to sort items in a list then submit the order back into the database.
But the code doesn't work in Firefox, or Chrome. It jumps and then clears out the contents of the list. It's been use开发者_开发问答d since 2002 works very fine in IE only..
var list;
function moveUp() {
list = document.forms[0].lists;
var index = list.selectedIndex;
if (index > 0) {
var item = list.options[index];
list.remove(index);
list.add(item, index - 1);
}
}
function moveDown() {
list = document.forms[0].lists;
var index = list.selectedIndex;
if (index > -1 && index < list.options.length - 1) {
var item = list.options[index];
list.remove(index);
list.add(item, index + 1);
}
}
function doSubmit() {
var s = "";
list = document.forms[0].lists;
for (var i = 0; i < list.options.length; i++) {
s += list.options[i].value + " ";
}
document.forms[0].order.value = s;
return false;
}
The problem is with list.add(item,index)
. This is non standard and works only in IE. For Chrome and Firefox, you should create an Option element using document.createElement("option")
. Take a look at an example code here
list.add(item, index + 1);
The second argument to HTMLSelectElement#add
is supposed to be a sibling option, not an index. Unfortunately, IE's add()
method does not implement the standard. This changes in IE8 Standards Mode.
To avoid the problem you could using plain old insertBefore
instead.
document.forms[0].lists is not defined in Firefox or Chrome. I'm not exactly sure what this is, but if those don't support it then it's probably a non-standard naming convention that IE does.
You're better off getting access to your list by using document.getElementById() and giving the list an id value.
For future reference, debugging with Firefox is done very easily with Firebug, you should check it out if you want to do Javascript development.
精彩评论