2014-10-28 105 views
0

onSubmit標籤似乎沒有工作。我試圖在網頁上點擊提交按鈕時調用submit()javascript函數。代碼如下:提交表單時提交函數沒有被調用

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <link rel="stylesheet" href="login.css"> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
    <script src="jquery.serializeJSON.min.js"></script> 
</head> 
<body> 
<script type="text/javascript"> 
    function submit() { 
    ....... 
    } 
</script> 
    <div class="login-container"> 
    <div class="title">Login Form</div> 
    <div class="form-fields"> 
     <form name="login-form" id="login-form" onSubmit="return submit()"> 
     <input type="text" name="username" id="username" placeholder="Username" required></input> 
     <input type="password" name="password" id="password" placeholder="Password" required></input> 
     <input type="submit" value="Log in" id="submit-button"></input> 
     </form> 
    </div> 
    </div> 
</body> 
+0

不知道你爲什麼關閉''標籤 – epascarello 2014-10-28 20:14:17

回答

2

有一個命名衝突。

形式具有內置的功能本機可與

<form id="x" onsubmit="console.log(submit);"><input type="submit"/></form> 

可以看到當你看到在控制檯上,你會看到

function submit() { [native code] } 

所以,當你調用提交()您所呼叫那原生提交功能aka document.getElementById("login-form").submit();而不是你的。爲了解決它,請更改名稱。

將函數名稱更改爲提交以外的內容。

function xSubmit(){ 

} 

<form name="login-form" id="login-form" onSubmit="return xSubmit()"> 
-2

它應該是小寫的s。

<form name="login-form" id="login-form" onsubmit="return submit()">

更多信息退房http://www.w3schools.com/jsref/event_onsubmit.asp

編輯: 對不起,我做了一些測試,發現它是名稱提交。 看看這個小提琴http://jsfiddle.net/9z95chze/

你也不應該說退貨

+2

不會有所作爲。它可以OnSuBmIt,它仍然可以工作。 – epascarello 2014-10-28 20:14:38

+0

並隨着你的編輯:如果你想取消表單提交,你確實需要返回。 – epascarello 2014-10-28 20:20:58

+0

哦,那是真的。我的錯。我通常儘量避免內聯JS,只是做一個返回false。感謝您的洞察力。 – user1600704 2014-10-28 20:24:44

0

不能使用 「提交」 作爲函數名。提交是一個JavaScript關鍵字。簡單地將你的功能重新命名爲別的。

function submitForm() { 
    console.log('I work now'); 
} 

<form name="login-form" id="login-form" onSubmit="return submitForm()"> 
+0

它保留在哪裏? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar – epascarello 2014-10-28 20:20:06