Dropdown currentIndex onchange

2019-04-25 09:42发布

there is a dropdown with 5 options. Currently,option 2 is selected.The user selects option 4 now.The onchange event gets fired which is caught in a JS function listening for onchange on the select.

In the JS function, I can check easily the index of the option selected by the user using the selectedIndex property.However, I want to also know what was the original value that the user changed it from.

Is there a property that persists basically the original value i.e. option 2 in this case.

3条回答
该账号已被封号
2楼-- · 2019-04-25 10:07

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

查看更多
放荡不羁爱自由
3楼-- · 2019-04-25 10:09

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;

查看更多
萌系小妹纸
4楼-- · 2019-04-25 10:15

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();
查看更多
登录 后发表回答