jquery – When changing select in val() shows the already selected value, but how to take the old one?

Question:

At

$('select').on('change', function() {
  var val = $(this).val(); // Показывает значение выбранное сейчас
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="name">
      <option value="1" selected>Мото</selected>
      <option value="2">Авто</selected>
    </select>

And if I had selected: "moto" before the selection, how to determine this within the change event?

Answer:

Let's use the focus event for the first save and then just update:

(function(){
    let previous;

    $("select").on('focus', e => previous = e.target.value).change(e => {
        // Прошлое значение value
        console.info(previous);

        // Необходимо обновить, иначе последующие смены не будут работать
        previous = e.target.value;
    });
}());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="name">
  <option value="1" selected>Мото</option>
  <option value="2">Авто</option>
</select>
Scroll to Top