I have a Select input type with 3 options and want to prompt an Alert window when any option is selected.
This alert has to put the execution of the selected option on hold and give a warning like: “Unsaved changes will be lost. Are you sure you want to continue?”, then I want the option to ‘Cancel’ the execution or to press ‘OK’ and execute.
How can I add a Cancel option inside the alert so it doesn’t execute the selected option and stays on the previously selected option?
See my code below and in the JSFiddle
HTML:
<p> Choose your formation: </p>
<select id="formation" name="formation" onchange="myFunction(formation)">
<option value="1"> 1-1-2 </option>
<option value="2"> 1-2-1 </option>
<option value="3"> 2-1-1 </option>
</select>
<p>
You chose the following formation: <spam id="demo"> X</spam>.
</p>
Javascript:
function myFunction(formation) {
alert("Unsaved changes will be lost. Are you sure you want to continue?")
if(document.getElementById('formation').value == "1") {
document.getElementById("demo").innerHTML = "1-1-2";
}
if(document.getElementById('formation').value == "2") {
document.getElementById("demo").innerHTML = "1-2-1";
}
if(document.getElementById('formation').value == "3") {
document.getElementById("demo").innerHTML = "2-1-1";
}
}