Reputation: 1495
I am learning web development using Django
and have some problems in where to put the code taking chage of whether to submit the request in the HTML code
.
Eg. There is webpage containing a form
(a blog) to be filled by the user, and upon click on the Save button,there is a pop up asking whether you want to confirm
or not. If click on confirm
, then the request is sent.
I searched and find this javascript
code.
<script type="text/javascript">
function clicked() {
alert('clicked');
}
<input type="submit" onclick="clicked();" value="Button" />
But I guess this is not the correct function as it seems to me that whenever you click on the Button, the request will be submitted. So How can I delay the submit request until user has confirm the submit?
Upvotes: 82
Views: 236873
Reputation: 11
Add the onClick function to the button
<input type="submit" onclick="return confirm('Are you sure?')" />
Upvotes: 1
Reputation: 7760
You can use onclick
in the submit button:
<button type="submit" onclick="return confirm('Are you sure?');"/>Delete</button>
You can also use onsubmit
in the form:
<form action="/" method="POST" onsubmit="return confirm('Are you sure?');">
<button type="submit"/>Delete</button>
</form>
Upvotes: 1
Reputation:
For a Django form, you can add the confirmation dialog inside the form tag:
<form action="{% url 'delete' %}" method="POST" onsubmit="return confirm ('Are you sure?')">
Upvotes: 6
Reputation: 31
Another option that you can use is:
onclick="if(confirm('Do you have sure ?')){}else{return false;};"
using this function on submit button you will get what you expect.
Upvotes: 3
Reputation: 11805
The most compact version:
<input type="submit" onclick="return confirm('Are you sure?')" />
The key thing to note is the return
-
Because there are many ways to skin a cat, here is another alternate method:
HTML:
<input type="submit" onclick="clicked(event)" />
Javascript:
<script>
function clicked(e)
{
if(!confirm('Are you sure?')) {
e.preventDefault();
}
}
</script>
Upvotes: 230
Reputation: 1027
I believe you want to use confirm()
<script type="text/javascript">
function clicked() {
if (confirm('Do you want to submit?')) {
yourformelement.submit();
} else {
return false;
}
}
</script>
Upvotes: 41
Reputation: 150
<script type='text/javascript'>
function foo() {
var user_choice = window.confirm('Would you like to continue?');
if(user_choice==true) {
window.location='your url'; // you can also use element.submit() if your input type='submit'
} else {
return false;
}
}
</script>
<input type="button" onClick="foo()" value="save">
Upvotes: 3
Reputation: 359786
Use window.confirm()
instead of window.alert()
.
HTML:
<input type="submit" onclick="return clicked();" value="Button" />
JavaScript:
function clicked() {
return confirm('clicked');
}
Upvotes: 7