js實現表單提交submit(),onsubmit

一般表單的提交有兩種方式,一是直接經過html的form提交,代碼以下:html

<form action="" method="" id="forms">
    <input type="text" name="username" value="" />
    <input type="password" name="pwd" value="" />
    <input type="submit" value="提交"/>
</form>

但有時候咱們會出於安全角度考慮,給用戶輸入的密碼進行加密,方法一就沒辦法解決這個問題,這時候咱們同常會選擇另外一種方法,使用javaScript來進行表單提交,代碼入下:java

<!--HTML-->
<form action="" method="" id="test_form">
    <input type="text" name="username" value="" />
    <input type="password" name="pwd" value="" />
    <button type="button" onclick='doSubmitForm()'>提交<button/>
</form>


<script>
var form = document.getElementById('test_form');
//再次修改input內容

form.submit();
</script>

這種方法有個缺點就是,打亂正常的表單提交程序,一般用戶輸入完成後點擊回車鍵就能夠提交,可是這個方法實現不了,因此,使用下面的方法即可以解決這個問題,,經過form自身的onsubmit方法,來觸發提交,而後進行input的修改:瀏覽器

<!--HTML-->
<form id='test_form' action='' method='' omsubmit='return checkForm()'>
    <input type='text' name='username' value=''/>
    <input type='password' name='pwd' value =''/>
    <button type='submit'>提交<button/>
<form/>

<script>
function checkForm(){
    var form = document.getElementById('test_form');
    //可在此修改input            
    //進行下一步
    return true;
}
<script/>

注意,checkForm()方法中,return true時,表單纔會正常提交,爲false時,瀏覽器將不會提交,一般是用戶的密碼輸入錯誤時,終止提交。安全

以前說過,爲安全考慮用戶提交時,通常對密碼進行加密處理,代碼以下:加密

<!--HTML-->
<form id='test_form' action='' method='' omsubmit='return checkForm()'>
    <input type='text' name='username' value=''/>
    <input type='password' name='pwd' id='pwd' value =''/>
    <button type='submit'>提交<button/>
<form/>

<script>
function checkForm(){
    var pwd= document.getElementById('pwd');
   pwd.value= toMD5(pwd.value);            
    //進行下一步
    return true;
}
<script/>

這種作法看上去沒問題,可是當用戶輸入完成後,提交會發現密碼框的 * 會由幾個瞬間變成 32個,這是因爲MD5加密形成的(MD5有32個字符);若是想避免出現這種狀況,須要充分利用到<input type='hidden'>,代碼以下:
spa

 

<!--HTML-->
<form id='test_form' action='' method='' omsubmit='return checkForm()'>
    <input type='text' name='username' value=''/>
    <input type='password'  id='input_pwd' value =''/>
    <input type='hidden' name='pwd' id='md5_pwd' value=''/>
    <button type='submit'>提交<button/>
<form/>

<script>
function checkForm(){
    var input_pwd= document.getElementById('input_pwd');
    var md5_pwd= document.getElementById('md5_pwd');
     md5_pwd.value= toMD5(input_pwd.value);            
    //進行下一步
    return true;
}
<script/>

 

注意,<input type='password'/>是用戶輸入密碼的input框並,沒有設置 name 屬性,而是給 <input type='hidden' /> 設置了 name='pwd',這樣表單提交只會提交帶有name屬性的輸入框,從而解決了上面的那個問題。code

相關文章
相關標籤/搜索