2012-12-12 50 views
1

我有一個表格如何從JavaScript提交表單中獲取信息?

<form name="loginForm" method="POST"> 
    Username: <input type="text" name="username" value="" /> 
    <br /> 
    Password: <input type="password" name="password" value="" /> 
    <input type="submit" name="submitButton" /> 
</form> 

如何採取上述信息打提交按鈕後,並做一些與所述數據?如,

<script> 
    function checkLogin(){ 
    //some code here 
    } 
</scipt> 

我真的很想知道如何使用SUBMIT按鈕,而不僅僅是onClick。

+1

那麼,如果你只使用提交,它進入服務器。如果這不是你想要的,那麼onClick有什麼問題? – RonaldBarzell

回答

3

使用onSubmit事件:

HTML:

<form name="loginForm" method="POST" onsubmit="checkLogin()"> 
    Username: <input type="text" name="username" value="" /> 
    <br /> 
    Password: <input type="password" name="password" value="" /> 
    <input type="submit" name="submitButton" /> 
</form> 

腳本:

function checkLogin(){ 
    // If you return "false" it will stop the form from being submitted 
} 
2

您可以爲表單指定一個onsubmit函數。

<form name="loginForm" method="POST" onsubmit="checkLogin()"> 
在功能

然後,像:

function checkLogin() { 
    var username = document.forms["loginForm"]["username"]; 
    // validate the form. Return false and the form will not be posted to server. 
} 
+0

另外,checkLogin的返回值確定請求是否發送到服務器。返回false以防止將表單發佈到服務器。 – BeWarned

1

您將在下面的方式使用$。員額{

$.post(URL_TO_YOUR_SCRIPT, { username: $("#username").val(), 
    password: $("#password).val() }, 
    function(data) { 
      alert(data); 
    }); 

實現這一點,你將不得不放棄的ID到您的輸入框如

<input type="text" name="username" id="username" /> 
<input type="password" name="password" id="password" /> 

乾杯!

+0

這是一個jQuery答案,OP沒有指示使用它。 – SReject

+0

我忘了提及您需要使用$ .post的jQuery.js。 –

+0

也爲了防止頁面刷新並重定向到操作頁面,您可以爲您的提交按鈕設置一個單擊事件: $('input [type =「submit」]')。live('click',function(e){ e.preventDefault(); checkLogin(); }); –