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! :)
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.
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.
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.
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);
});
})();
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With