使用javascript处理文本区域时出现问题

时间:2010-01-06 13:25:12

标签: javascript

脚本不起作用: 请找出原因n补救措施?

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;
        }

    }

表格是:

<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>

3 个答案:

答案 0 :(得分:4)

尝试检查值的长度而不是元素的长度。

答案 1 :(得分:1)

检查

document.complain.complain.value.length

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

此外,我认为textareas没有maxlength属性。

答案 2 :(得分:0)

这一行:

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

错了。

应该是:

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

另外,作为一般原则,我建议使用局部变量来使代码更具可读性。另外,我建议以相同的方式做同样的事情,所以如果你必须比较最大长度,那么也要使用length属性来检查最小长度。最后,像这样的函数很难遵循,因为你有多个退出点。我建议做类似的事情:

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;
}