我无法在提交时访问表单

时间:2016-01-11 14:30:15

标签: javascript forms

我无法通过JavaScript访问表单。标题中的Javascript代码,位于<head>标记之间。

错误消息告诉我表单不存在。所以我使用了onload evenement,但它没有解决问题。

<head>
<script>
window.onload = function() {

document.getElementsByName('form_login').onsubmit = function(){ }

} ;

window.onload = function() {

document.getElementsByName('form_login')[0].onsubmit = function(){ }

} ;
</script>
</head>


<body>
<form action="/login" method="post" name="form_login">
<input type="text" tabindex="1" name="username" id="username" size="25" maxlength="40" value="" />
<input type="password" tabindex="2" id="password" name="password" size="25" maxlength="25" />
<input type="checkbox" name="autologin" id="autologin" tabindex="4" checked="checked" />
<input type="hidden" name="redirect" value="" />
<input type="hidden" name="query" value="" />
<input type="submit" name="login" tabindex="6" value="Connexion" />
</form>
</body>

2 个答案:

答案 0 :(得分:2)

只需将const添加到onsubmit="login(this)"元素,并在该页面上加载的javascript代码中定义此功能(form)。

&#13;
&#13;
login
&#13;
function login(form) {
  // ... some code here
};

// ... OR ...

loginForm.onsubmit = function() {
  // ... some code here
  // ... return false is required to prevent form submitting
  return false;
};
&#13;
&#13;
&#13;

答案 1 :(得分:1)

没有错误。请参阅fiddle

将您的脚本放在<script>标记内,如下所示:

<head>
<script>
    //The script
</script>
</head>

然后,在<script>&amp; </script>

onload=function(){ 
    document.getElementsByName('form_login')[0].onsubmit=function(e){
        e.preventDefault();//avoid page refreshing to see the following alert
        alert("Yeah! I see, it works.")//indicate that it works
    }
}