I have a select box, and I\'d like to add a confirm before changing it to a specific option. Example:
Here's a more verbose and commented version of lonesomeday's accepted answer that prompts for confirm on each change and uses .data() rather than jQuery.data().
It might help people with understanding the logic a bit more.
Accompanying jsFiddle is here.
// set the initial data value
$(document).ready(function() {
var my_select = $("#my_select");
my_select.data("current", "foo");
});
// when selecting another option
$('select').change(function() {
var $this = $(this);
var selected = $this.val();
logit($this, selected, 1); // log data to screen
// if clicking cancel on the confirm dialog
if (!confirm('Are you sure?')) {
logit($this, selected, 2); // log data to screen
// set the select's value to the stored data value
var previous_data_value = $(this).data("current");
$this.val(previous_data_value);
// escape the onchange function
return false;
}
// if clicking OK, update the data value to the chosen option
logit($this, selected, 3); // log data to screen
$this.data("current", $this.val());
});
// helper functions only below
$(document).on("click", ".clicker", function() {
var my_select = $("#my_select");
alert(my_select.data("current"));
});
function logit($this, selected, instance) {
var current_data_value = $this.data("current");
if (instance === 1) {
var value_log = "you selected the value: " + selected + "";
$(".container_2").append(value_log);
var data_log = "the previous value was: " + current_data_value + "";
$(".container_2").append(data_log);
} else if (instance === 2) {
$(".container_2").append("you clicked Cancel, value was reverted to: " + current_data_value + "");
}
if (instance === 3) {
$(".container_2").append("you clicked OK, value was changed from '" + current_data_value + "' to '" + selected + "'");
}
$(".container_2").append("------------------------------------------------------");
}
* {
box-sizing: border-box;
}
select {
width: 200px;
float: left;
}
.clicker {
width: 200px;
float: left;
}
.container_1 {
margin: auto;
width: 400px;
background: lightgray;
padding-top: 10px;
padding-bottom: 10px;
}
.container_1:after {
clear: both;
content: " ";
height: 0;
display: block;
}
.container_2 {
width: 400px;
height: 300px;
overflow-y: auto;
border: 1px solid gray;
padding: 10px;
margin: auto;
background: #222;
}
span {
display: block;
margin-bottom: 5px;
color: lime;
font-family: arial;
font-size: 12px;
}