2013-05-01 74 views
-2

我有一個功能來檢查是否有任何文本在電子郵件字段中輸入,但它不工作。
我不知道我缺少什麼。輸入驗證功能不起作用

這是我的方式:

<fieldset> 
    <legend>Contact Information</legend> 
    <form action="" id="contactInfo" onsubmit="checkform()">First Name: 
     <input type="text" name="fname" id="fname"> 
     <br />Last Name: 
     <input type="text" name="lname" id="laname"> 
     <br />Email: 
     <input type="text" name="email" id="email"> 
     <br /> 
     <button type="submit">Submit</button> 
    </form> 
</fieldset> 

這是我的功能在一個單獨的文件.js

function checkform(form) { 
    if (document.form.email.value = "") { 
     alert("Please enter your email address."); 
     document.form.email.focus(); 

     return false; 
    } 

    return true; 
} 
+0

看到你在'checkForm'函數中有'form'參數,你應該像這樣傳遞它:'

'那麼你可以簡單地使用'form。改爲使用email.value ==「」'。 – Nope 2013-05-01 21:52:16

回答

3

Here is a demo

HTML

<fieldset> 
    <legend>Contact Information</legend> 
    <form id="contactInfo" onsubmit="checkform()"> 
     First Name: <input type="text" name="fname" id="fname"><br /> 
     Last Name: <input type="text" name="lname" id="laname"><br /> 
     Email: <input type="text" name="email" id="email"><br /> 
     <button type="submit">Submit</button> 
    </form> 
</fieldset> 

的JavaScript

function checkform(form) 
{ 
    console.log(form); 
    if(document.forms[0].email.value == ""){ 
     alert("Please enter your email address."); 
     document.form.email.focus(); 
     return false; 
    } 
    return true; 
} 
+1

我試過這個,但沒有奏效。 – 2013-05-01 21:41:15

+0

查看演示。究竟是什麼問題? JS錯誤? – abhshkdz 2013-05-01 21:42:36

+1

只是想出來。我沒有添加額外的=標誌。謝謝 – 2013-05-01 21:47:26

1

使用這個代替:

document.forms[0].email.value 

,使用形式ID檢索值。

function checkform(form) { 
    if (document.forms[0].email.value == "") { 
     alert("Please enter your email address."); 
     document.forms[0].email.focus(); 
     return false; 
    } 
} 

fiddle

+0

我做了這一個,但它仍然無法正常工作。調試器給我一個錯誤。它是TypeError:document.form是undefined – 2013-05-01 21:42:19

+0

你看過小提琴嗎? – NullPointerException 2013-05-01 21:42:50

0

傳遞的形式,作爲參數thischeckForm()功能。這樣你可以使用多種形式的checkForm()函數。像這樣:

<fieldset> 
    <legend>Contact Information</legend> 
    <form action="" id="contactInfo" onsubmit="checkform(this)">First Name: 
     <input type="text" name="fname" id="fname"> 
     <br />Last Name: 
     <input type="text" name="lname" id="laname"> 
     <br />Email: 
     <input type="text" name="email" id="email"> 
     <br /> 
     <button type="submit">Submit</button> 
    </form> 
</fieldset> 

然後你可以從你的驗證功能訪問表單元素出document.前綴,像這樣:

function checkform(form) { 
    if (form.email.value == "") { 
     alert("Please enter your email address."); 
     form.email.focus(); 

     return false; 
    } 

    return true; 
} 

(此外,請務必檢查form.email.value == ""form.email.value = ""這是分配運營商)。