JQuery check if select box has changed

I would like to do jQuery validation if a select box has changed. If it changed, set a warning message (changed), if it returns by default, set another warning message (default).

$('select').on('change',function () {
    var isDirty = false;

    $('select').each(function () { 
        var $e = $(this);      
        if (!$e[0].options[$e[0].selectedIndex].defaultSelected) {
        isDirty = true;
        }    
    });

    if(isDirty == true) { 
        alert("has changed");
    } else {
        alert("default value");          
    }
});

      

Please advise if this is correct.

+3


source to share


2 answers


You don't need an inner loop each

. Plus $(this)[0]

can only be optimized for this

:



$('select').on('change', function () {
        
    var isDirty = !this.options[this.selectedIndex].defaultSelected;

    if (isDirty) {
        alert("has changed");
    } else {
        alert("default value");
    }
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="" id="">
    <option value="1">Label 1</option>
    <option value="2" selected>Label 2</option>
    <option value="3">Label 3</option>
    <option value="4">Label 4</option>
</select>
      

Run code


+4


source


I would do something like:

HTML:

<select data-default="one" id="the-select">
  <option>one</option>
  <option>two</option>
</select>

      



JavaScript:

$('#the-select').change(function() {
    var changed = $(this).val() != $(this).data('default');
    alert(changed ? 'changed' : 'not changed');
});

      

+1


source







All Articles