Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
172
rated 0 times [  177] [ 5]  / answers: 1 / hits: 43335  / 14 Years ago, tue, november 30, 2010, 12:00:00

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! :)


More From » html

 Answers
9

Using straight JavaScript and DOM, something like this (live example):



var box, oldValue;

// Get a reference to the select box's DOM element.
// This can be any of several ways; below I'll look
// it up by ID.
box = document.getElementById('theSelect');
if (box.addEventListener) {
// DOM2 standard
box.addEventListener(change, changeHandler, false);
}
else if (box.attachEvent) {
// IE fallback
box.attachEvent(onchange, changeHandler);
}
else {
// DOM0 fallback
box.onchange = changeHandler;
}

// Our handler
function changeHandler(event) {
var index, newValue;

// Get the current index
index = this.selectedIndex;
if (index >= 0 && this.options.length > index) {
// Get the new value
newValue = this.options[index].value;
}

// **Your code here**: old value is `oldValue`, new value is `newValue`
// Note that `newValue`` may well be undefined
display(Old value: + oldValue);
display(New value: + newValue);

// When done processing the change, remember the old value
oldValue = newValue;
}


(I'm assuming all of the above is inside a function, like a page load function or similar, as in the live example, so we're not creating unnecessary global symbols [box, oldValue, 'changeHandler`].)



Note that the change event is raised by different browsers at different times. Some browsers raise the event when the selection changes, others wait until focus leaves the select box.



But you might consider using a library like jQuery, Prototype, YUI, Closure, or any of several others, as they make a lot of this stuff a lot easier.


[#94790] Saturday, November 27, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
frederickmohamedw

Total Points: 21
Total Questions: 123
Total Answers: 105

Location: The Bahamas
Member since Tue, Apr 27, 2021
3 Years ago
frederickmohamedw questions
Wed, Sep 23, 20, 00:00, 4 Years ago
Sat, Jul 18, 20, 00:00, 4 Years ago
Sun, Apr 26, 20, 00:00, 4 Years ago
Sat, Jan 11, 20, 00:00, 4 Years ago
Fri, Dec 27, 19, 00:00, 4 Years ago
;