Reputation: 363
So I have an select option field, and what I change the option of select field a confirm message will show. My problem is how do I prevent of changing the value of select option field after cancelling the confirmation message.
$('.changeScoreFem').on('change', function(){
if (confirm('Are you sure to change this score?')) {
//continue to change the value
} else {
//else do not change the selecoption field value
}
});
Upvotes: 1
Views: 5223
Reputation: 171700
You can do this by storing current value of select, then undo it as needed.
Following uses a custom event to store the data and that custom event is also triggered on page load in case you pass selected items from server
var $sel = $('.changeScoreFem').on('change', function(){
if (confirm('Are you sure to change this score?')) {
// store new value
$sel.trigger('update');
} else {
// reset
$sel.val( $sel.data('currVal') );
}
}).on('update', function(){
$(this).data('currVal', $(this).val());
}).trigger('update');
Upvotes: 6
Reputation: 21499
You need to store selected option in variable and if confirm canceled, reselect it.
var selected = $(".changeScoreFem option:selected");
$(".changeScoreFem").on("change", function(e){
if (confirm("Are you sure to change this score?"))
selected = $(this).find("option:selected");
else
selected.prop("selected", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="changeScoreFem">
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
Upvotes: 2