简体   繁体   中英

Need help in Javascript onChange event

On change of a dropdown value, I need to confirm whether the user wants to change the value or changed it by mistake.

If user clicks on OK then system should apply the modification, otherwise the value should not change.

As of now I have written code as follows:

document.getElementById("dropdownid").onchange = function (){ 

  var a = confirm("Do you want to change");

  if (a == true){
    return true;
  }

  if (a == false){
    return this;
  }

}

here am getting the confirm box but regardless of whether if I press OK or Cancel, the dropdown always shows the new value.

Please try this:

document.getElementById("dropdownid").onchange = function (){ 
     var a = confirm("Do you want to change");
    if (a == true)
       {
         return true;
       }
    if (a == false)
       {
         return false;
       }
    }

check this fiddle

var drop = document.getElementById("dropdownid"); 
var selected =drop.options[drop.selectedIndex]; //save selection initially
drop.onclick = function (e){
selected = drop.options[drop.selectedIndex]; // save current selection 
}
drop.onchange = function (e){
var a = confirm("Do you want to change");
if (a == false) // no need to check for true
   {
       selected.selected=true; // if cancel, set the existing selected option
   }
}

You can undo the selection like this:

document.getElementById("dropdownid").onchange = function (){
    if (!confirm("Do you want to change")) {
        if (typeof this.prevVal=='undefined') {
            this.prevVal=this.options[0].value;
            for (var i=0;i<this.options.length;i++)
                if (this.options[i].defaultSelected)
                    this.prevVal=this.options[i].value;
        }
        this.value=this.prevVal;
    } else {
        this.prevVal=this.value;
    }
}

Basically you save in an attribute the previously selected value, and you search for the default value if not changed yet.

try using this code

document.getElementById("dropdownid").onchange = function (eve){ 
   var a = confirm("Do you want to change");
   if (a == true){
     return true;
   }
   if (a == false){
       eve.preventDefault();
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM