Reputation: 2804
I have a HTML select field. Where one option is selected
. If I select any other change
even fires and confirm prompt is shown.
What I want is when user cancel the confirmation aka conf
is false
. I want to reset back to the previous selected option. But currently the new option is selected.
<select id="mySelect">
<option>Foo0</option>
<option seleted="selected">Foo1</option>
<option>Foo3</option>
<option>Foo4</option>
<option>Foo5</option>
<option>Foo6</option>
</select>
jQuery(document).ready(function($){
var select = $('#mySelect');
select.change(function(){
var conf = confirm('Are You Sure?');
if(!conf){
// reset the select back to previous
return;
}
// do stuff
});
});
Upvotes: 4
Views: 5086
Reputation: 46
put your oldvalue as data and get it back when it selected wrong...
var select = $('#mySelect');
select.click(function(){
$(this).data("oldval", this.value);
}).change(function(){
var conf = confirm('Are You Sure?');
if(!conf){
$(this).val($(this).data("oldval"));
}
});
Upvotes: 1
Reputation: 796
You can use jQuery's .focus()
to store the previously selected option on focus, which will be triggered before the selection is changed.
jQuery(document).ready(function($){
var select = $('#mySelect');
var previouslySelected;
select.focus(function(){
previouslySelected = this.value;
}).change(function(){
var conf = confirm('Are You Sure?');
if(!conf){
// reset the select back to previous
this.value = previouslySelected;
return;
}
// do stuff
alert('Doing stuff');
});
});
Demo: http://jsfiddle.net/9mAHP/1/
Upvotes: 0
Reputation: 2557
You weren't looking for something like this, were you? Just store the value, then grab it when you need it.
$(document).ready(function($){
var select = $('#mySelect');
var current = $('#mySelect').find(":selected").text();
select.change(function(){
var conf = confirm('Are You Sure?');
if(!conf){
select.val(current);
} else{
// do stuff
}
current = $('#mySelect').find(":selected").text();
// reset the select back to previous
return;
});
});
DEMO: http://jsfiddle.net/Qw6K9/
Upvotes: 0
Reputation: 3962
I created a jsfiddle for you here: http://jsfiddle.net/CZ8F9/
I am just saving the previous index.
jQuery(document).ready(function($){
var index = $('#mySelect').prop('selectedIndex');
var select = $('#mySelect');
select.change(function(e){
alert(index)
var conf = confirm('Are You Sure?');
if(!conf){
$('#mySelect').prop('selectedIndex',index);
// reset the select back to previous
return false;
}
else{
index= $('#mySelect').prop('selectedIndex');}
// do stuff
});
});
Upvotes: 3