Link to home
Start Free TrialLog in
Avatar of BR
BRFlag for Türkiye

asked on

alert before form submission

Dear, Experts,

I have a form and submit button which sends the form data to the action page

What I want to do is, to make an alert before the user sends the form to the action page

when the user press the submit button, I want to ask, "are you sure"?

if the user says yes, I submit the form, else I do nothing

if you suggest me something better instead of alert, please let me know. Thank you
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

You've tagged this as AJAX, so you could just call the alert before making the AJAX request. You'd need to use the confirm() box:

if (confirm('Are you sure?')) {
    // Make your AJAX call
}

Open in new window

If you need more info, then show us the code you use for submitting the form
Avatar of BR

ASKER

I found this code on the web,
but it submits the form even if the user says cancel,
If the user clicks cancel, it should not submit the form

<script type="text/javascript">
    function clicked() {
       if (confirm('Do you want to submit?')) {
           yourformelement.submit();
       } else {
           return false;
       }
    }
</script>

Open in new window

OK. That should work, but you'll need to make sure you're calling it correctly. In your form you need to return the result of your function call:

<form onsubmit="return clicked()" method="post" name="yourformelement">
...

Open in new window

Avatar of BR

ASKER

I found another code, it works,

do you recommend me to use it?
<script>
function clicked(e)
{
    if(!confirm('Siparişinizi Onaylıyor musunuz?'))e.preventDefault();
}
</script>

<form id="form1" name="form1" method="post" action="Untitled-1.html" >
  <label for="bir"></label>
  <input type="text" name="bir" id="bir" />
<input type="submit" onclick="clicked(event)" />
</form>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of BR

ASKER

thank you Chris