tags:

views:

121

answers:

3

the script is not working: please find the reason n remedy?

function validate() {
        if(document.complain.complain.value == '' || document.complain.complain_subject.value == ''){
            alert("Hey! you can't left a field blank!");
            return false;
        }
 else if(document.complain.complain.length >100) {

            alert("Sorry!post the complain within 100 characters");
            return false;
            }

        else{
            return true;
        }

    }

the form is:

<form name="complain" method="POST" action="complains.jsp" onsubmit="return validate();">
<table>
    <tr>
        <td><input type="text" name="complain_subject"
            value="Complain Subject here" maxlength="30"></td>
    </tr>
    <tr>
        <td><textarea rows="6" name="complain" cols="73"
            value="Complain body here" maxlength="100"></textarea></td>
    </tr>
    <tr>
        <td><input type="submit" value="complain" name="operation"><input
            type="reset" value="Reset" name="B2"></td>
    </tr>
</table>
</form>
+4  A: 

Try checking the length of the value rather than the length of the element.

tvanfosson
+1  A: 

Check for

document.complain.complain.value.length

or

document.getElementById ( "complain" ).value.length

Also I don't think there is a maxlength attribute to textareas.

rahul
ya maxlength attribute to text area doesnt work.i just wrote it to remember the allocation size of this field in the database
Robin Agrahari
thanx a lot.this really helped.thax a lot again
Robin Agrahari
A: 

This line:

else if(document.complain.complain.length >100) {

is wrong.

It should read:

else if(document.complain.complain.value.length >100) {

Also, as a general principle, I would advise to use local variables to make the code more readable. In addition, I would recommend to do the same thing in the same way, so if you have to compare for maximum length, then use the length property also to check for the minimum length. Finally, a function like this can get very hard to follow because you have multiple exit points. I'd suggest to do something like:

function validate() {
    var form = document.complain, 
        complaintMinLength = 1, complaintMaxLength = 100
        complaintSubjectMinLength = 1,
        complaintLength = form.complain.value.length,
        complaintSubjectLength = form.complain_subject.value.length,
        valid, msg
    ;
    if (complaintLength < complaintMinLength || 
        complaintSubjectLength < complaintSubjectMinLength) {
        valid = false;
        msg = "Hey! you can't leave a field blank!";
    } else if (complaintLength > complaintMaxLength) {
        valid = false;
        msg = "Sorry! Your message exceeds the maxumum length of " + complaintMaxLength + " characters.";
    } else {
        valid = true;
    }
    if (!valid){
        alert(msg);
    }
    return valid;
}
Roland Bouman