1. 程式人生 > >HTML form 避免(回車)表單自動提交

HTML form 避免(回車)表單自動提交

1、JavaScript提交表單程式碼

 <span style="font-size:14px;">   <span style="font-size:18px;">
      <span style="color:#FF0000;"> document.forms["myform"].submit(); </span> 
       or   
       document.myform.submit();//myform為表單名
    </span>  </span>
2、當表單中包含input的text、password等時按下回車鍵(Enter)會自動提交表單,有時需要這種功能,有時不需要這一功能。禁用回車自動提交
攻略之一:

 1)用button按鈕替換submit按鈕;

 2)給button按鈕新增onclick事件,同時在onclick事件中提交表單;

<script language="javascript">
	function defineSubmit(btn)
	{
		document.testForm.submit();
	}
</script>

<form name="testForm" method="post" action=" ">
	username:<input type="text" name="username"/>
	password:<input type="password" name="password"/>
	<input type="button" name="submitName" onclick="defineSubmit(this)" value="submit1"/>
</form>
改進:

假如一個表單中需要有多個按鈕,不同的按鈕提交給不同的處理程式,可進行如下改進:

<script language="javascript">
	function defineSubmit(btn)
	{
		if("submit1" == btn.value)
		{
			<span style="color:#FF0000;"><span style="background-color: rgb(255, 255, 255);">document.testForm.action</span></span>="firstAction";
		}
		else
		{
			<span style="color:#FF0000;">document.testForm.action</span>="secondAction";
		}
		
		document.testForm.submit();
	}
</script>
<form <span style="color:#FF0000;">name="testForm"</span> method="post">
		username:<input type="text" name="username"/>
		password:<input type="password" name="password"/>
		<input type="button" name="submitName" onclick="defineSubmit(this)" value="submit1"/>
		<input type="button" name="submitName" onclick="defineSubmit(this)" value="submit2"/>
</form>

原文出處:http://blog.csdn.net/shutear/article/details/7914243