Let explore the article “confirm change event on confirmation for a dropdown“.To prevent a select box from changing without user confirmation, the system displays a JavaScript confirmation message before altering the dropdown. In this scenario, before modifying the selected option, the user receives a confirmation message, ensuring their readiness for the change. If the user confirms, the dropdown option changes accordingly; otherwise, the select option remains unchanged.. So here question comes, how can we will do this ? I have a solution that confirms the change event on confirmation for a dropdown and provides the exact solution. The change event triggers only after the value of the select option has been changed. If you click “OK,” the system will change your option. However, if you click “Cancel,” your option will remain unchanged.

confirm change event on confirmation for a dropdown

I am not using any jQuery for this type of criticality; I have simply done it through simple JavaScript to avoid including any library files like jQuery, and I manage that through two variables.

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.

<!DOCTYPE html>
	<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>
		
<form>
     <div>Please Select option:
        <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>

Live Demo


Click To Run

Hope You enjoy this articleconfirm change event on confirmation for a dropdown

confirm change event on confirmation for a dropdown
Tagged on:             

Leave a Reply

Your email address will not be published. Required fields are marked *