2010-11-30 22 views
9

¿Cómo puedo recuperar el nuevo valor seleccionado y el valor seleccionado previamente con JavaScript cuando se llama onChange o un evento similar?¿Cómo obtener el valor seleccionado anterior y nuevo de una opción elemento DOM con JavaScript?

<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; 
    // ... 

¡Gracias! :)

+0

¿algún código para mostrar? – wajiw

Respuesta

8

Uso de JavaScript y DOM recta, algo como esto (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; 
} 

(estoy suponiendo que todo lo anterior es dentro de una función, como una función de carga de la página o similar, ya que en la live example, así que no estamos creando innecesarios símbolos globales [box, oldValue, 'changeHandler`].)

Tenga en cuenta que el evento change se eleva por diferentes navegadores en diferentes momentos. Algunos navegadores plantean el evento cuando la selección cambia, otros esperan hasta que el foco abandona el cuadro de selección.

Pero es posible considerar el uso de una biblioteca como jQuery, Prototype, YUI, Closure o any of several others, ya que hacen un montón de estas cosas mucho más fácil.

+0

Me encantaría usar un Framework de JavaScript. ¡Soy un gran fanático de Prototype! :) Pero no podemos presentar uno de ellos en este momento. :(Gracias por su consejo, le dejaré saber si funciona. –

+0

gracias funciona bien :) –

5

vistazo aquí: Getting value of select (dropdown) before change Creo que el mejor,

(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); 
    }); 
})(); 
+0

respuesta duplicada https://stackoverflow.com/a/4076949/1644320 –

2

El siguiente fragmento de código puede ayudar a

<html> 
    <script type="text/javascript"> 
     this.previousVal; 
     function changeHandler(selectBox) 
     { 
      alert('Previous Val-->'+selectBox.options[this.previousVal].innerHTML) 
      alert('New Val-->'+selectBox.options[selectBox.selectedIndex].innerHTML) 
      this.previousVal=selectBox.selectedIndex; 
     } 
    </script> 
    <body> 
     <select id="selectBox" onchange="changeHandler(this)"> 
      <option>Sunday</option><option>Monday</option> 
      <option>Tuesday</option><option>Wednesday</option> 
     </select> 
     <script type="text/javascript"> 
      var selectBox=document.getElementById("selectBox") 
      this.previousVal=selectBox.selectedIndex 
     </script> 
    <body> 
</html> 
+0

¿Cómo es este código mejor que la respuesta aceptada? ¿Por qué es preferible usar el evento onchange en línea? –

0

A continuación trabajó para mí. Agregue a continuación dos eventos para seleccionar la etiqueta HTML: -

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' 
Cuestiones relacionadas