简体   繁体   English

在Javascript onChange事件中需要帮助

[英]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. 这是确认对话框,但是无论我按OK还是Cancel,下拉菜单始终显示新值。

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();
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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