dedi wibisono dedi wibisono - 14 days ago 5
HTML Question

How to set alert for two 'value' by jQuery if the 'value' is equal

I want to set alert when the value is same. And the value selected is back to previous value
Here is my HTML:

<select name="" id="from">
<option value="DPS">Denpasar</option>
<option value="BGK">Bangkok</option>
<option value="MOS">Moscow</option>
</select>

<select name="" id="to">
<option value="DPS">Denpasar</option>
<option value="BGK">Bangkok</option>
<option value="MOS">Moscow</option>
</select>


and my JS

$("#to").val("BGK");
var fromCity = "";
var toCity = "";
$('#from,#to').change(function(){
var fromCityVal = $("#from").val();
var toCityVal = $("#to").val();
if (fromCityVal == toCityVal){
alert("city of origin may not be the same as the destination city!");
}
else {
//here's problem, what should I do?
$("#from").val();
}
});


I try this, but not success, What should I do? or any suggestion? Thank you
Here's my code in jsfiddle: https://jsfiddle.net/dedi_wibisono17/hx1voew9/

Answer

You must storage the previous value as a backup. You can make it with a focus event:

    $("#to").val("BGK");
    var item = '';
    var previous = '';
    $('#from,#to').on('focus', function () {
      previous = this.value;
      item = this;
    }). change(function(){
    var fromCityVal = $("#from").val();
            var toCityVal = $("#to").val();
            if (fromCityVal == toCityVal){
                alert("city of origin may not be the same as the destination city!");
                $(item).val(previous);
            } else {
      //here's problem, what should I do?
                $("#from").val();
            }
    })
Comments