2012-12-12 49 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(); }); –