2010-05-19 38 views
0

我學習jQuery和在 寫兩個字段的簡單數據驗證HTML表單:removeClass不會在第二DIV標籤工作

<FORM name="addpost" id="addpost" method="post" action="/add"> 
    <TABLE border=0 width="100%"> 
     <TR> 
      <TD>Topic</TD> 
      <TD>  
       <DIV id="topic"> 
        <INPUT type=text name="topic" id="topic" size="72" maxlength="108"/> 
       </DIV>  
      </TD> 
     </TR> 
     <TR> 
      <TD>Comments</TD> 
      <TD> 
       <DIV id="topiccontent">   
        <TEXTAREA rows="12" cols="48" name="content" id="content"> 
        </TEXTAREA> 
       </DIV> 
      </TD> 
     </TR> 
     <TR> 
      <TD> 
       <INPUT type="submit" value="Send"> 
      </TD> 
     </TR> 
    </TABLE> 
</FORM> 

下面是檢查數據輸入的jQuery腳本從上面的表格:

$('#addpost').submit(function(){  
    if($('#topic').val()==""){ 
     $('#topic').addClass('hierror'); 
     return false;} 
    else{$('#topic').removeClass('hierror');} 

    if($('#topiccontent').val()==""){ 
     $('#topiccontent').addClass('hierror'); 
     return false;} 
    else{$('#topiccontent').removeClass('hierror');} 
}); 

下面是hierror類的CSS:

.hierror{border-style:solid; border-width:12px; border-color:#FF0000;} 

問題是('#topic').removeClass('hierror')有效,但('#topiccontent').removeClass('hierror')沒有。

請問您能幫我嗎?

回答

4

有兩件事情錯您的標記:

不要大寫(使用<div><DIV>)型HTML實體。

每個標籤都必須有唯一的ID(因此divinput需要有不同的ID)。在jQuery的檢查('#topic input').val(),但隨後從@Konrad Garus在談論的普遍問題進行('#topic').removeClass()

3

除此之外,您的具體問題是,你的JS代碼由#topiccontent元,這恰好是使用.val()進行驗證一個div。您的textarea元素是您要執行驗證的元素,其名稱爲content