网页Form只有一个input框时,按回车后表单就直接提交了,输入检测函数不起作用

来源:互联网 发布:电脑屏幕防蓝光软件 编辑:程序博客网 时间:2024/05/16 11:01

下例中的 testForm 表单中只有一个名称为 testInput 输入框,当 testInput 输入框处于聚焦状态时,按回车表单直接就提交了,而没有通过输入检测函数 checkInput() 进行合法性检查,当表单中有多个输入框时没有此问题,请问这种问题有没有什么办法解决?

<form name="testForm" method="post" action="testAction">   请输入6位数字:<input name="testInput" type="text" tabindex="1" maxlength="6">   <a href="javascript:void(0);" onclick="javascript:checkInput();">测试</a></form><script type="text/javascript">   //输入检测函数   function checkInput(){      if(!(/^(\d{6})$/).test(document.testForm.testInput.value)){         alert("请检查输入是否有误!");         document.testForm.testInput.focus();         return false;      }      document.testForm.submit();      return true;   }</script>

你可以尝试以下方法来解决:
1、在 Form 中加入提交检测

<form name="testForm" method="post" action="testAction" onsubmit="javascript:checkInput();">   请输入6位数字:<input name="testInput" type="text" tabindex="1" maxlength="6">   <a href="javascript:void(0);" onclick="javascript:checkInput();">测试</a></form>

2、加一个不显示的输入框

<form name="testForm" method="post" action="testAction">   请输入6位数字:<input name="testInput" type="text" tabindex="1" maxlength="6">   <input type="text" name="keyPressSubmitKiller" style="display:none;">   <a href="javascript:void(0);" onclick="javascript:checkInput();">测试</a></form>

3、在输入框加入回车检测

<form name="testForm" method="post" action="testAction">   请输入6位数字:<input name="testInput" type="text" tabindex="1" maxlength="6" onkeydown="javascript:if(event.keyCode==13){checkInput();}">   <a href="javascript:void(0);" onclick="javascript:checkInput();">测试</a></form>

0 0
原创粉丝点击