emre
emre

Reputation: 45

How to compare dropdown previous value with current value using jquery

I have a drop down and I want to compare its previous and current value. If previous value is same with current value (I mean no change happened) I would make another logic at if statement.

 function filter() {
        var id= "ctl00_plchldContent_dropdown1";
        var current;
        var latest;
        var dropdown = document.getElementById(element.id);
        dropdown.onchange('change', function () {
            current = $('#' + id + ' option:selected').val().trim();
        }).change(function () {
            latest = $('#' + id + ' option:selected').val().trim();
        });

       if(current != previous){
           //logic here
         }
    });

Although drop down is not null, I am getting Expected when onchange event object error. How can I fix it? I am very new for jquery btw. Thanks

Upvotes: 0

Views: 1078

Answers (2)

Hien Nguyen
Hien Nguyen

Reputation: 18975

You can declare global variable to store selected item, after change set selected as newSelected value

var selected = $("#ctl00_plchldContent_dropdown1").val();

$("#ctl00_plchldContent_dropdown1").change(function() {

  let newSelected = $("#ctl00_plchldContent_dropdown1").val();
  if (newSelected != selected) {
    alert("Changed");
    selected = newSelected;
  }
});

var selected = $("#ctl00_plchldContent_dropdown1").val();

$("#ctl00_plchldContent_dropdown1").change(function() {
  
  let newSelected = $("#ctl00_plchldContent_dropdown1").val();
  if (newSelected != selected) {
    alert("Changed");
    selected = newSelected;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="ctl00_plchldContent_dropdown1">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

Upvotes: 0

matthias_h
matthias_h

Reputation: 11416

You could do it by saving the previously clicked option in a data-attribute at the select and compare the currently clicked option to it. It's also necessary to have a click() event on the options instead of a change() event at the select as this would not be called if the selected option is the same option as before.

$("#ctl00_plchldContent_dropdown1 option").on("click", function() {
  let selected = $(this).val();
  if ($(this).parent("select").attr("data-previous") == selected) {
    alert("Same value as previously.")
  }
  $(this).parent("select").attr("data-previous", selected);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="ctl00_plchldContent_dropdown1">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

Upvotes: 0

Related Questions