2011-02-28 51 views
0

喜 我想兩個檢查兩個字段 如果兩個字段的值相同,則其顯示一個消息二我,我有一個代碼,但檢查兩個表單字段

它不工作,你能告訴我什麼撥錯這個代碼

<script type="text/javascript"> 
function checkForm(form1){ 
    if(form1.field1.value == form1.field2.value){ 
     alert(" values are identical"); 
     form1.field1.focus(); 
     return true; 
    }else{ 
     return false; 
    } 
} 
</script> 
<form name="form1" method="POST" action="" > 
<input type="text" name="field1"> 
<input type="text" name="field2"> 
<input type="submit" onClick="return checkform1(this);" > 
</form> 
+1

對於初學者來說,你打電話'checkform1'和你的功能被命名爲'checkForm'。 – zdyn 2011-02-28 06:22:05

回答

3

更改,如果條件這樣

 
if(document.form1.field1.value==document.form1.field2.value) 
+0

我改變了它,但沒有消息將顯示 – amit 2011-02-28 06:22:38

+0

當你在你的按鈕 – 2011-02-28 06:28:32

+0

的onclick事件中調用它時,並且你在提交按鈕的onclick事件中調用函數checkform1時,將它從函數中刪除。但是你已經將函數定義爲checkForm。在打電話時使表格名稱類似。這也是你的拼寫錯誤 – 2011-02-28 06:31:10

2

你打電話checkform(),但不會在任何位置定義。另外,checkform1(this)使用該按鈕作爲元素form1,它將所有東西都擰緊。使用this.parentNode,它將形式作爲參數傳遞。

這裏的一些工作代碼:

<script> 
    function checkForm(form1) { 
    if (form1.field1.value == form1.field2.value) { 
     alert(" values are identical"); 
     form1.field1.focus(); 
     return true; 

    } else { 
     return false; 
    } 
} 
</script> 

<form name="form1" method="POST" action="" > 
    <input type="text" name="field1"> 
    <input type="text" name="field2"> 
    <input type="submit" onClick="return checkForm(this.parentNode);" > 
</form> 
0

您需要在您的形式選擇前加document.。而且您的方法名稱與您通過點擊事件調用的方法不符。

,我已經修復它,這裏包括一個例子:http://jsfiddle.net/jomanlk/Fu2wJ/1/

function checkForm(form1) { 
    if (document.form1.field1.value == document.form1.field2.value) { 
     alert(" values are identical"); 
     document.form1.field1.focus(); 
     return false; 


    } 
    else { 
     return true; 
    } 
} 
<form name="form1" method="POST" action="" > 
    <input type="text" name="field1"> 
    <input type="text" name="field2"> 
    <input type="submit" onClick="return checkForm();" > 
</form> 
+1

他不使用'文件。「他是(認爲)他是通過它作爲參數。見Blender的答案。 – zdyn 2011-02-28 06:25:46

+0

ohhh。我沒有注意到(這)被通過。這是有道理的。爲了清楚起見,我將從我的答案中刪除「this」引用 – JohnP 2011-02-28 06:27:13

0

除了事實checkForm1功能不存在,主要的問題在於

<input type="submit" onClick="return checkform1(this);" >

這裏this是指input而不是form

爲了使你的代碼的工作改變函數名checkForm

<input type="submit" onClick="return checkform1(this.form);" >