0

我的问题是,如果每个问题有任何空白文本输入,我如何才能显示验证消息?

这是一个小提琴,因此您可以对其进行测试:http: //jsfiddle.net/cbyJD/87/

下面是validation()函数代码:

function validation() {

    // only keeping track of the final message
    var alertValidation = "",
        // toggle for showing only one error
        showOnlyOneError = true;

    $("input[data-type='qmark']").each(function(i) {  
        var questions = $(this).attr("data-qnum");
        var marks = parseInt($("[class*=q" + (i+1) + "_ans_text]").text()); 
        var txtinput = $(this).val(); 

        // the message for this question
        var msg = '';

        if (txtinput == '') {
            msg += "\n\u2022 You have not entered in a value in all the Indivdiaul Marks textbox \n";
        }

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

        // if there is an error for the question, add it to the main message
        if (msg.length) {
            alertValidation += alertValidation.length ? '\n\n' : '';
            alertValidation += "You have errors on Question Number: " + questions + "\n";
            alertValidation += msg;
            // stop if we only care about the first error
            return !showOnlyOneError;
        }
    });

    // show the error messages
    if (alertValidation != "") {
        alert(alertValidation);
        return false;
    }

    return true;
}
4

1 回答 1

0

这是您的“第一次错误后返回”。如果您填写了第一个框但它有其他错误,您将只收到这些错误 - 第二个框不会被检查,您永远不会发现它是空的。最明显的解决方法是showOnlyOneError = false.

如果这不是您想要的,那么您必须showOnlyOneError更详细地解释所需的语义。

(另外,提示:将错误推入数组然后将它们加入"\n\n"比每次检查消息字符串是否为空要轻松得多。)

于 2012-12-20T00:34:15.713 回答