Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get previous and new selected value from a option DOM element with JavaScript?

How can I retrieve the new selected value and the previous selected value with JavaScript when onChange or similar event is called?

<select size="1" id="x" onchange="doSomething()">
  <option value="47">Value 47</option>
  ...


function doSomething() {
  var oldValue = null; // how to get the old value?
  var newValue = document.getElementById('x').selected.value;
  // ...

Thank you! :)

like image 918
Thomas Avatar asked Nov 30 '10 16:11

Thomas


People also ask

Which method is used to retrieve the option values from dropdown?

We can extract all the options in a dropdown in Selenium with the help of Select class which has the getOptions() method. This retrieves all the options on a Select tag and returns a list of web elements.

How can we get elements from the DOM in JavaScript?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.

How do I find the value of a DOM element?

HTML DOM getAttribute() method is used to get the value of the attribute of the element. By specifying the name of the attribute, it can get the value of that element. To get the values from non-standard attributes, we can use the getAttribute() method.


2 Answers

Look here: Getting value of select (dropdown) before change I think the better,

(function () {
    var previous;

    $("select").focus(function () {
        // Store the current value on focus, before it changes
        previous = this.value;
    }).change(function() {
        // Do something with the previous value after the change
        alert(previous);
    });
})();
like image 119
Harvey Avatar answered Sep 16 '22 15:09

Harvey


Below worked for me. Add below two events to your select HTML tag:-

onFocus='this.oldValue = this.value'; //if required in your case add this line to other events like onKeyPressDown and onClick. 
onChange = 'alert(this.oldValue); this.value=this.oldValue'
like image 27
Dev Avatar answered Sep 20 '22 15:09

Dev