Reputation: 481
What I'm trying to do is make a confirm dialog box popup when I press to create an item in my view. From what I understand from reading other posts (correct me if I'm wrong) is by using jquery. I'm not very familiar with jquery/javascript so I'm doing my best to understand what I'm doing. The code i found online is this.
<form method="post">
<input id="Create" name="Common" type="submit" value="Create" />
<script type="text/javascript">
$(document).ready(function () {
$("#Create").click(function (e) {
// use whatever confirm box you want here
if (!window.confirm("Are you sure?")) {
e.preventDefault();
}
});
});
How it is right now every time I press the button it fires my POST create method in my controller right away without showing a dialog box. Can someone explain me why that happens and how i can fix it. I have tried adding code where //use whatever confirm box you want here
is written but I don't really know what I'm looking for or what it needs to be written there.
Posts i have read
Where i got the above code from
Delete ActionLink with confirm dialog
ASP.NET MVC ActionLink and post method
Upvotes: 3
Views: 11686
Reputation: 50728
What you have should work fine. I use the on method but click method should have the same effect. You don't need to specify window.confirm, just confirm will work for this too.
$("#Create").on("click", function (e) {
// use whatever confirm box you want here
if (!confirm("Are you sure?")) {
e.preventDefault();
}
});
Make sure that:
$("#Create").length
If it doesn't return 1, that is a problemUpvotes: 0
Reputation: 62301
One way is to use <input type="button" />
. Then call submit()
for the form.
<form method="post" id="sampleform">
<input id="Create" name="Common" type="button" value="Create" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#Create").click(function (e) {
if (confirm("Are you sure?")) {
console.log('Form is submitting');
$("#sampleform").submit();
} else {
console.log('User clicked no.');
}
});
});
</script>
</form>
If you use ASP.NET MVC, you might want to consider using Html.BeginForm Html Helper.
@using (Html.BeginForm("Login", "Account", FormMethod.Post, new { Id = "sampleform"}))
{
<input id="Create" name="Common" type="button" value="Create" />
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script type="text/javascript">
... Same as above
</script>
Upvotes: 2
Reputation:
try by adding onclick
<form method="post">
<input id="Create" name="Common" type="submit" value="Create" onclick="DeleteFunction()"/>
...
</form>
<script>
function DeleteFunction()
{
if(confirm('Are you sure?'))
return true;
} else {
return false;
}
}
</script>
Upvotes: 0