2011-12-30 36 views
0

我想驗證通過JavaScript提交的表格。這個想法是,表單提交了一個可接受值的集合列表,只有這些值可以工作。所以如果該字段是黑色的,它會提醒該ID不正確。如果該字段的輸入不在列表中,則會顯示該ID不正確。我已經接近了。我只需要一點點方向。驗證與列表中的JavaScript

這裏是我的代碼:

script type="text/javascript"> 
     function validateForm() 
     { 
      var x=document.forms["dispatch"]["ID1"].value; 
      var arr=["CA238", "Pete", "John"]; 
      if x==(.inArray(inputVal, arr) > -1) 
      { 
    alert("Correct Dispatcher ID Required"); 
    return false; 
    } 
} 
</script> 

<form id="form_242533" class="appnitro" name="dispatch" onsubmit="return validateForm()" method="post" action="<?php echo $_SERVER["PHP_SELF"]?>"> 
<li id="li_9" > 
      <label class="description" for="element_1">Dispatch ID</label> 
     <div> 
      <input id="element_1" name="ID1" class="element text medium" type="text" value=""/> Put your assigned dispatcher ID 
     </div> 
     </li> 

        <li class="buttons"> 
       <input type="hidden" name="Submit" value="Submit" /> 

       <input id="submit" class="button_text" type="submit" name="submit" value="Submit" /> 
       <input type="reset" /> 

     </li> 
      </ul> 
     </form> 
+0

「可接受值的集合列表」,呃?列表框如何? – James 2011-12-30 02:32:22

+0

表單提交背後的想法是一個用戶ID,每個允許提交表單的用戶在列表中都會有一個id(目前是數組),他們會在那裏放入ID,它會驗證是否讓表單提交,如果他們不沒有ID,表單不會提交併告訴他們該ID缺失或無效 – nate 2011-12-30 02:36:57

回答

2

更改此:

if x==(.inArray(inputVal, arr) > -1) 

這樣:

if ($.inArray(x, arr) == -1) 

如果你正在使用jQuery。


如果你沒有jQuery的網頁上,將其更改爲這個:

if (arr.indexOf(x) == -1) 

不過請注意,這種方法不會在IE < 9.使用the polyfill provided here工作增加indexOf支持舊版本的IE。

+0

已更改,但仍允許提交,無論空白輸入或錯誤輸入=/ – nate 2011-12-30 02:45:14

+0

@NathanDollinger - 您使用的是jQuery嗎? – 2011-12-30 02:46:09

+0

它只是JavaScript即時通訊新的,但我試過,但仍然沒有收到任何結果,可以有任何其他問題的腳本或形式其自身? – nate 2011-12-30 02:49:39