JavaScript表单提交 – 确认或取消提交对话框
对于一个带有警告的简单表单,询问字段是否填写正确,我需要一个这样做的函数:
-
当点击两个选项button时显示一个警告框:
- 如果单击“确定”,则表单被提交
- 如果点击取消,则提示框closures,表单可以调整并重新提交
我认为一个JavaScript的确认工作,但我似乎无法弄清楚如何。
我现在的代码是:
<script> function show_alert() { alert("xxxxxx"); } </script> <form> <input type="image" src="xxx" border="0" name="submit" onclick="show_alert();" alt="PayPal - The safer, easier way to pay online!" value="Submit"> </form>
一个简单的内联JavaScript确认就足够了:
<form onsubmit="return confirm('Do you really want to submit the form?');">
除非你正在做validation ,否则不需要外部函数 ,你可以这样做:
<script> function validate(form) { // validation code here ... if(!valid) { alert('Please correct the errors in the form!'); return false; } else { return confirm('Do you really want to submit the form?'); } } </script> <form onsubmit="return validate(this);">
function show_alert() { if(confirm("Do you really want to do this?")) document.forms[0].submit(); else return false; }
您可以使用JS确认function。
<form onSubmit="if(!confirm('Is the form filled out correctly?')){return false;}"> <input type="submit" /> </form>
<form onsubmit="return confirm('Do you really want to submit the form?');">
好的,只要将你的代码改成这样:
<script> function submit() { return confirm('Do you really want to submit the form?'); } </script> <form onsubmit="return submit(this);"> <input type="image" src="xxx" border="0" name="submit" onclick="show_alert();" alt="PayPal - The safer, easier way to pay online!" value="Submit"> </form>
这也是运行中的代码,只是让我们更容易看到它是如何工作的,只需运行下面的代码来查看结果:
function submitForm() { return confirm('Do you really want to submit the form?'); }
<form onsubmit="return submitForm(this);"> <input type="text" border="0" name="submit" /> <button value="submit">submit</button> </form>