如何在jquery中正确验证空文本输入

时间:2012-12-05 03:48:39

标签: jquery html

这是我验证html表的jQuery代码:

function validation() {

    var alertValidation = "";
    var _qid = "";
    var _msg = "";

    $("[class*='q']").each(function (i) {
        var questions = parseInt($("[class*=q" + i + "_qnum]").text());
        var marks = parseInt($("[class*=q" + i + "_ans_text]").text());
        var txtinput = $("[class*=q" + i + "_mark]").val();
        _qid = questions;
        _msg = "You have errors on Question Number: " + _qid + "\n";


        if (txtinput == '' || txtinput == null) {
            alertValidation += "\n\u2022 You have not entered in a value for all the Indivdiaul Marks textbox\n";
        } else if (marks < '0') {

            alertValidation = "Your Total Marks Remaining does not equal 0 \n\n\u2022 You Need To Remove " + Math.abs(marks) + " Marks";
        } else if (marks > '0') {

            alertValidation = "Your Total Marks Remaining does not equal 0 \n\n\u2022 You Have " + marks + " Marks Remaining";
        }

        if (alertValidation != "") {
            return false; //Stop the each loop 
        }

    });


    if (alertValidation != "") {
        alert(_msg + alertValidation);
        return false;
    }

    return true;
}

现在我觉得奇怪的是,如果剩余标记数量的验证大于0并且当标记剩余数量低于0时的验证在输出警报时完美地工作,因为它显示如下:

高于0:

You have errors on Question Number: 1
Your Total Marks Remaining does not equal 0 

• You Have 7 Marks Remaining

小于0:

You have errors on Question Number: 1
Your Total Marks Remaining does not equal 0 

• You Need To Remove 3 Marks

但是当我尝试验证“每个答案的标记”部分下的文本输入是否为空时,它会在下面显示以下消息:

You have errors on Question Number: NaN

• You have not entered in a value for all the Indivdiaul Marks textbox

为什么不能显示此验证的问题编号?

另外一个小问题是,即使我在“每个答案的标记”下的所有文本输入中输入了值,它仍然会显示上面的验证消息警告。为什么这样做呢?

下面是一个示例html表:

<table border='1' id='markstbl'>
<thead>
<tr>
<th class='questionth'>Question No.</th>
<th class='answermarksth'>Marks per Answer</th>
<th class='noofmarksth'>Marks Remaining</th>
</tr>
</thead>
<tbody>

<tr class="questiontd">
<td class="questionnumtd q<?php echo$questionId?>_qnum" name="numQuestion" rowspan="1">1 <input type="hidden" name="q1_ans_org" class="q1_ans_org" value="5"><input type="hidden" name="q1_ans" class="q1_ans" value="5"></td>
<td class="answermarkstd">
<input class="individualMarks q1_mark"  q_group="1" name="answerMarks[]" class="individualtext" type="text" onkeypress="return isNumberKey(event)" maxlength="3" />
</td>
<td class="noofmarkstd q1_ans_text"  q_group="1" rowspan="1"><strong>5</strong></td>
</tr>
    </tbody>
</table>

2 个答案:

答案 0 :(得分:0)

您可以使用length来检查属性是否包含空文本而不是!=“”

alertValidation.length > 0

您可以查看以下代码

parseInt($("[class*=q" + i + "_qnum]").text());

如果这个$(“[class * = q”+ i +“_ qnum]”)。text()未定义,那么parseInt将只返回NaN

由于

答案 1 :(得分:0)

尝试使用 alert($(“[class * = q”+ i +“_ qnum]”)。text());

或使用google chrome或firebug进行调试,

我相信 each()捕获您的Web中不存在的类,或者它包含无法解析为Int的字符,空格,这会在脚本中导致NaN,尝试检查它