2013-05-31 58 views
0

爲什麼我的簡單JavaScript驗證不起作用。我想檢查默認文本是否與默認值(Keyword(s))相同,然後提交帶有空參數的表單。簡單的JavaScript表單驗證提交不起作用

<form method="get" id="search_form" action="http://somesampleurl.com" onsubmit="return validation();"> 
<input name="s_rawwords" value="Keyword(s)" id="search_field" class="search_field" type="text"> 
<input name="s_freeloc" value="City, State or Zip" id="search_field2" class="search_field" type="text"> 
<input value="" id="search_button" type="submit"> 
</form> 
<script type="text/javascript"> 
    function validation(){ 
     var search_key = document.getElementById("search_field").value 
     alert(search_key); 
     if(search_key =="Keyword(s)"){ 
      alert("step2"); 
      search_key = ""; 
     } 
    } 
</script> 
+1

返回TRUE;或'FALSE'和它的工作 – karthikr

+0

不,沒有奏效。 – tv4free

+0

對不起。它確實有效。 – tv4free

回答

1

試試這個代碼:

function validation(){ 
    var search_key = document.getElementById("search_field").value; 
    alert(search_key); 
    if(search_key =="Keyword(s)"){ 
     alert("step2"); 
     document.getElementById("search_field").value = ""; 
    } 
    return true; 
} 
3

你的函數永遠不會返回truefalse,所以也沒有任何驗證。當輸入無效並且您不希望提交表單時返回false

看到這裏MSDN documentation

+0

+1以供解釋和參考 – iamnotmaynard