如何使用确认对话框取消选择菜单选项?
这个想法是,当用户更改选择菜单时,系统会提示他们确认自己的选择。如果他们选择“取消”,则选择菜单将返回其先前选择的值。如果他们选择“确定”,则选择菜单会按预期运行。
以下是我正在处理的代码:
HTML:
<select class="selector" name="selector1">
<option value="yes">Yes</option>
<option value="no" selected="">No</option>
<option value="maybe">Maybe</option>
</select>
<select class="selector" name="selector2" >
<option value="yes">Yes</option>
<option value="no" selected="">No</option>
<option value="maybe">Maybe</option>
</select>
的JavaScript
var selects = document.querySelectorAll('.selector');
var lastSelected = {};
for (i = 0; i < selects.length; i++) {
var select = selects[i];
lastSelected[select.name] = select.options[select.selectedIndex];
select.addEventListener('change', function (e) {
lastSelected = select.options[select.selectedIndex];
if (confirm("Are you want to choose this?") == true) {
return;
} else {
select.value = lastSelected[select.name];
}
});
}
我不完全确定为什么这不起作用,我们非常感谢任何帮助。 这是我正在研究http://jsfiddle.net/je36eu78/2/
的小提琴n.b 我想在原生JavaScript(无jquery)中执行此操作
答案 0 :(得分:2)
您在此处覆盖lastSelected
:
lastSelected = select.options[select.selectedIndex];
另一种方法(将前一个值存储为select的属性)
var selects = document.querySelectorAll('.selector');
for (i = 0; i < selects.length; i++) {
var select = selects[i];
select.defaultValue=select.value;
select.addEventListener('change', function (e) {
if (confirm("Are you want to choose this?") == true) {
this.defaultValue=this.value;
} else {
this.value=this.defaultValue;
}
});
}
答案 1 :(得分:1)
尝试下面的代码段
var select = document.querySelectorAll('.selector');
for (i = 0; i < select.length; i++) {
select[i]['last'] = select[i].options[select[i].selectedIndex].value;
(function(i){
select[i].onchange = function(){
if(confirm("Sure?")){
select[i]['last'] = this.value;
}else{
this.value = select[i]['last'];
}
};
})(i);
}
工作jsBin