开发者

Javascript dropdownlist

How can I get the pr开发者_C百科evious selected index on change event of dropdown list using Javascript.


No, it is not possible, but you can use a variable inside onchange event that tracks the previous selection

Example:

var previousSelected;
function track(d){
  if(typeof previousSelected != 'undefined'){
    alert("Previous selected value " + previousSelected );
  }
  previousSelected = d.selectedIndex;
  alert("selected value " + d.selectedIndex); 
}


Place a meta variable in the ul or ol object that is the index of the last selected item so that when you goto the item again you can just ask for that property again and, presto, you know the index of the last selected item.

A common way of placing a meta variable inside an object is by adding a class to the last item that was selected with javascript and then finding the list item with that class when you want to see which one was selected. I see JQuery users doing this alot (btw you should be using JQuery to help with all of your javascript).

For example, to mark the last item as selected:

$('ul li:last').addClass('selected');

Then to find it again:

$('ul li.selected')

Its actually a pretty easy way of tracking this kind of code.


You could have a javascript global variable which will track this value. So when the change event is trigerred you would have the new value and the old one. Then you would update the global variable with the new value.

Here's an example pseudo code:

var selectedValue = '';
document.getElementById('someId').onchange = function() {
    var newValue = this.value;

    // TODO: compare with the old value

    selectedValue = newValue;
};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜