tags:

views:

44

answers:

2

Hi all,

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?

+4  A: 

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 div and input need to have different IDs). In jQuery check ('#topic input').val(), but then execute ('#topic').removeClass()

Konrad Garus
+3  A: 

Aside from the general problems that @Konrad Garus is talking about, your particular problem is that your JS code is performing the validation by using .val() on the #topiccontent element, which happens to be a div. Your textarea element, which is the one you want to perform the validation on, is named content.

Franci Penov