I am learning JQuery and writing a simple data validation for the two fields in
a HTML form:
<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>
Here is the JQuery script for checking the data input from the form above:
$('#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');}
});
Here is the CSS for the hierror class:
.hierror{border-style:solid; border-width:12px; border-color:#FF0000;}
The problem is that ('#topic').removeClass('hierror') works but ('#topiccontent').removeClass('hierror') doesn’t.
Could you help me please?
There are two things wrong about your markup:
Do not type HTML entities in uppercase (use
<div>not<DIV>).Each tag must have unique ID (so
divandinputneed to have different IDs). In jQuery check('#topic input').val(), but then execute('#topic').removeClass()