How to make cancel confirmation message on button click event using JQuery in MVC4 razor application
JQuery is a very powerful language and can be used to make application effective. I have added simple code which can be used very commonly during code development. This is useful for MVC4 , JQuery beginners.
Many of functionalities are common during code development, cancel button functionality is one of them. I have developed it in MVC4 application in which I have used JQuery.
Add btnsubmit in view (.cshtml) page which should be as follows:
<p>
<input type="submit" value="Cancel" name ="Command" id ="btnsubmit"/>
</p>
JQuery code is as follows:
<script type="text/javascript">
$(document).ready(function ()
{
$("#btnsubmit").click(function (event)
{
if ($("#btnsubmit").val() == "Cancel")
{
var output_value = confirm("Are you sure you want to cancel?")
if (output_value)
{
$('#Command').submit();
}
else
{
event.preventDefault();
}
}
});
});
</script>
If multiple buttons are present on the form then whenever page gets posted, id and value are used to recognize which button has been clicked. If user selects cancel then confirmation box will be gone.
If output_value is true then submit is performed. This way we can prevent POST action of form if user selects cancel.