If you would like to prevent a select box from being changed if not confirmed by user. So here the case is before changing select option , user will be get a message as javascript confirmation to make sure user is ready to change dropdown else select option won’t be changed and will be as it is. So here question comes, how can we will do this ? Because change event is only triggered once the value of the select option has actually been changed. But I have the solution which confirm change event on confirmation for a dropdown and provides exact solution like if will click ok then your option will be changed else if you click cancel then your option won’t be changed.

For this type of criticality I am not using any jquery , I juts have done through simple javascript for avoiding to include any library files like jQuery and that is managed through two variables like old and new. So if user confirms then old value will be replaced by new value else current value will be still same old value. please look to the below javascript code that I have done.
1 2 3 4 5 6 7 8 |
box = document.getElementById('select_option'); var answer = confirm("Are you sure ?)."); if(answer) { oldValue = newValue; }else{ box.value = oldValue; } |
so take our full example to make sure our logic is working and to make us fully understandable that how all works.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
< !DOCTYPE html> <html> <head> <title>confirm change event on confirmation for a dropdown</title> <script> window.onload = function() { var box, oldValue=''; box = document.getElementById('select_option'); if (box.addEventListener) { box.addEventListener("change", changeHandler, false); } else if (box.attachEvent) { box.attachEvent("onchange", changeHandler); } else { box.onchange = changeHandler; } function changeHandler(event) { var index, newValue; index = this.selectedIndex; if (index >= 0 && this.options.length > index) { newValue = this.options[index].value; } var answer = confirm("Are you sure want to change option ?"); if(answer) { oldValue = newValue; }else{ box.value = oldValue; } } } </script> </head> <body> <form> <div> <span>Please Select option: </span> <select id="select_option"> <option value="">Please Select option</option> <option value="apple">Apple</option> <option value="pear">Pear</option> <option value="banana">Banana</option> <option value="orange">Orange</option> </select> </div> </form> </body> </html> |
Live Demo
Hope You enjoy this article