2013-04-22 23 views
0

我有默認值0 2個文本框和一個提交button.Before提交我打電話javascript函數onSubmit="return(validate_myfrm());以下」。我是無法與價值0.But驗證text_1text_2默認值0被驗證。如何在使用javascript提交前驗證文本框?

function validate_myfrm() 
{ 

    var ans; 
    if(document.myfrm.txt_1.value=="" ||document.myfrm.txt_1.value==0) 
     { 
       ans=confirm("Do you still want to continue with value 0 for text 1?"); 
       if(ans== true) 
        { 
        document.myfrm.txt_1.value=0; 
        document.myfrm.txt_2.focus(); 
        } 
       else 
        { 
        document.myfrm.txt_1.focus(); 
        } 
       return false; 
    } 

    if(document.myfrm.txt_2.value=="" ||document.myfrm.txt_2.value==0) 
      { 
       ans=confirm("Do you still want to continue with value 0 for text 2?"); 
       if(ans== true) 
        { 
        document.myfrm.txt_2.value="0"; 
        return true; 
        } 
       else 
        { 
         document.myfrm.txt_2.focus(); 
        } 
        return false; 
      } 
    return true; 

}

如果我返回true; document.myfrm.txt_2.focus();後的頁面將被重定向到下個頁面確認值txt_2.Pls幫助

回答

0

document.myfrm.txt_bb1.value == 0

應該是:document.myfrm.txt_1.value == 0

也:

一旦設置一回,該功能將結束,在你的函數返回的虛假或真實出發了。

第一個如果值爲「」或0時根據您的條件將始終返回false。由於它返回false,函數將結束並返回false。

編輯:

這裏簡單的驗證例如:

<form id="myfrm" name="myfrm" onSubmit="return(validate_myfrm());"> 
    <input type="text" name="txt_1" value="" /> 
    <input type="text" name="txt_2" value="" /> 
    <input type="submit" value="submit" /> 
</form> 
<span id="result"></span> 

<script> 

function validate_myfrm() 
{ 
    if(document.myfrm.txt_1.value!="" && document.myfrm.txt_2.value!="") 
    { 
     return true;  
    } else { 
     document.getElementById("result").innerHTML="Error fields cannot be empty"; 
     return false; 
    } 
} 
</script> 

記住這一點,每當你在一個函數中使用的回報,它會停止功能和返回值集。

+0

好.. @ Marc我編輯過。 – Atit 2013-04-22 09:31:22

0

你的第一個條件應該是這樣的

if(document.myfrm.txt_1.value=="" ||document.myfrm.txt_1.value==0) 
{ 

} 
+0

@ The-Val ..我不明白你的意思。我應該在第一個條件之後留下空白嗎? – Atit 2013-04-22 09:38:37

+0

不,它只是指出你要設置適當的變量名稱,正如前面提到的Marc,但我沒有看到它。 :) – 2013-04-22 09:45:07

0

使用否則如果Instaed如果功能現在將提交之前驗證。

function validate_myfrm() 
{ 

    var ans; 
    if(document.myfrm.txt_1.value=="" ||document.myfrm.txt_1.value==0) 
     { 
       ans=confirm("Do you still want to continue with value 0 for text 1?"); 
       if(ans== true) 
        { 
        document.myfrm.txt_1.value=0; 
        document.myfrm.txt_2.focus(); 
        } 
       else 
        { 
        document.myfrm.txt_1.focus(); 
        return false; 
        } 
    }else if(document.myfrm.txt_2.value=="" ||document.myfrm.txt_2.value==0) 
      { 
       ans=confirm("Do you still want to continue with value 0 for text 2?"); 
       if(ans== true) 
        { 
        document.myfrm.txt_2.value="0"; 
        return true; 
        } 
       else 
        { 
         document.myfrm.txt_2.focus(); 
        } 
        return false; 
      } 
    return true; 
    } 
}