Dropdown currentIndex onchange

旧城冷巷雨未停 提交于 2019-12-04 03:37:01

Just as a concept I put together the following - there may very well be a better way to do this:

var vals = [];

document.getElementById("colors").onchange = function(){
   vals.unshift(this.selectedIndex);
};

function getPrevious(){
  alert(vals[1]); // you'll need more logic here
                  // this is purposefully simplistic
}

--

<select id="colors">
   <option>Red</option>
   <option>Green</option>
   <option>Blue</option>
</select>

Closed-up Example:

I've tried to tie this all into the actual drop-down element itself. In all honesty, this is the first time I've ever add functions to the dropdown itself, so I cannot promise that this won't have consequences:

   var colors = document.getElementById("colors");
       colors.vals = [];
       colors.setPrevious = function() { this.vals.unshift(this.selectedIndex); }
       colors.getPrevious = function() { return this.vals[1]; }
       colors.onchange    = function() { this.setPrevious(); this.getPrevious(); }
       // set initial state
       colors.setPrevious();

No, you would need to persist that yourself in a js variable.

As told by dl, you can use simple hidden variable to hold the value.We can set the current value in hidden varaible.

<input type = "hidden" id = "previous" name = "previous"></input>

Use onfocus="setPrevious(this.id)" to set the current value

JS

function setPrevious(id) {
	document.getElementById("previous").value = document.getElementById(id).selectedIndex ;
}

Use Onchange() to check the confirm button output and set the "previous" value

document.getElementById(id).selectedIndex = document.getElementById("previous").value;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!