简体   繁体   English

如何使用JavaScript在同一页面上显示多个错误消息

[英]How to display multiple error messages on the same page using JavaScript

I am working on java script and i am stuck on one phase. 我正在研究Java脚本,并且停留在一个阶段。 In my project i have to validate all fields when the form is submitted and display error message on same page in order list above the form field. 在我的项目中,提交表单时,我必须验证所有字段,并在表单字段上方的顺序列表中的同一页上显示错误消息。 bellow is my code 波纹管是我的代码

function validation(){
    var errorMsg=new Array(); 
    //var errorMsg = "";
    if(document.getElementById("fullname").value = " "){
        errorMsg[0] = "Please Enter Full Name\n"
}
if(document.getElementById("street").value = " "){
        errorMsg[1]= "Please Enter Street Name\n"
}
if(document.getElementById("postcode").value = " "){
        errorMsg[2]= "Please Enter Postlecode\n"
}
if(document.getElementById("phone").value = " "){
        errorMsg[3]= "Please Enter Phone Number\n"
}
if(document.getElementById("email").value = " "){
        errorMsg[4]= "Please Enter Email Id\n"
}
if(errorMsg!=" "){
    var r =" ";
    for(var i=0;i<=errorMsg.length-1;i++){
    document.getElementById("error").innerHTML="<li>"+errorMsg[i]+"</li>"
    }   
    return false;
}
}
</script>

when i run this code it gives me only last value 当我运行此代码时,它只给我最后一个值

can anybody help me how to display error message on the top of the form? 有人可以帮助我如何在表单顶部显示错误消息吗?

You've got a mistake here: 您在这里有一个错误:

document.getElementById("error").innerHTML="<li>"+errorMsg[i]+"</li>"

You need to append errorMsg , not to assign it. 您需要附加errorMsg ,而不要分配它。 For example like this: 例如这样:

document.getElementById("error").innerHTML+="<li>"+errorMsg[i]+"</li>"

If you want to display the error message on the top of the page, you should create div, where you want, give to this div the id and set innerHtml to this div: 如果要在页面顶部显示错误消息,则应在所需的位置创建div,为该div提供ID,并将innerHtml设置为此div:

<div id="AllErrors"></div>

document.getElementById("AllErrors").innerHTML+="<li>"+errorMsg[i]+"</li>"

Also you could improve your validation and validate fields when a user is typing, not after he submitted all information. 另外,您可以在用户输入时(而不是在提交所有信息之后)改善验证和验证字段。

And by the way, you add errors in tag <li> . 顺便说一句,您在标签<li>添加了错误。 So, you know that you should also add <ol> or <ul> to make a list? 因此,您知道还应该添加<ol><ul>来创建列表吗?

You need to append each error to the existing .innerHTML rather than overwriting the existing: 您需要每个错误附加到现有的.innerHTML而不是覆盖现有的:

document.getElementById("error").innerHTML += "<li>"+errorMsg[i]+"</li>"
// note += instead of = here --------------^

Though can skip the loop altogether and just do this: 虽然可以完全跳过循环,但是只需执行以下操作:

document.getElementById("error").innerHTML = "<li>"+errorMsg.join("</li><li>")+"</li>";

(The .join() method puts all the array elements into a string separated by the specified text.) .join()方法将所有数组元素放入由指定文本分隔的字符串中。)

Also, if only some of your conditions are met your array will have undefined (missing) elements since you are explicitly setting specific indexes, which means you'll be adding <li> elements with "undefined" displayed in them. 另外,如果仅满足您的某些条件,则由于显式设置特定索引,数组将具有未定义(丢失)的元素,这意味着您将添加<li>元素,并在其中显示“未定义”。 You should do this instead: 您应该这样做:

    errorMsg.push("Please Enter Full Name\n");
    // OR
    errorMsg[errorMsg.length] = "Please Enter Full Name\n";

...either of which will add to the end of the array. ...这两个都将添加到数组的末尾。 Then to test if there were any errors do: 然后测试是否有任何错误:

if (errorMsg.length > 0)

Also the conditions in your if statements are all doing assignments because they use = where they should use === (or == ), and you are testing whether each field contains a single space: " " where I think you want to test if each field is empty by comparing to an empty string: "" . 另外,if语句中的条件都在进行赋值,因为它们使用= ,应该在其中使用=== (或== ),并且您正在测试每个字段是否包含单个空格: " " ,我认为您要在其中测试比较一个空字符串""每个字段都是空的。

I rewrote your code a bit. 我稍微重写了您的代码。 Here is what I changed: 这是我更改的内容:

  • Instead of checking that the value equals " " , I have used the ! 我没有检查值是否等于" " ,而是使用了! operator. 操作员。
  • I have used push on the array instead of appending by index. 我使用了对数组的push而不是按索引附加。 This means that there are no empty spots in your array. 这意味着您的阵列中没有空位。 push adds an element to the end of the array, irrespective of the index. push将元素添加到数组的末尾,而与索引无关。
  • I used a forEach loop on the array. 我在数组上使用了forEach循环。 This goes through all the enumerable elements, irrespective of how many there are. 这遍历了所有可枚举的元素,无论有多少。

So, the example: 因此,示例:

JS JS

// This could be done on form submit, I used a button for the fiddle.
document.getElementById("button").onclick = function () {   
    var errorMsg = new Array();

    if(!document.getElementById("fullname").value){
        errorMsg.push("Please Enter Full Name");
    }

    if(!document.getElementById("street").value){
        errorMsg.push("Please Enter Street Name");
    }

    if(!document.getElementById("postcode").value){
        errorMsg.push("Please Enter Postal Code");
    }

    if(!document.getElementById("phone").value){
        errorMsg.push("Please Enter Phone Number");
    }

    if(!document.getElementById("email").value){
        errorMsg.push("Please Enter Email Id");
    }

    var messageHtml = "";

    errorMsg.forEach(function (message) {
        messageHtml += "<li>" + message + "</li>";
    });

    document.getElementById("error").innerHTML = messageHtml;
};

See this fiddle: http://jsfiddle.net/M48gA/ 看到这个小提琴: http : //jsfiddle.net/M48gA/

您必须在if语句中使用=====代替=

That's because innerHtml of "error" always gets replaced.So only last value is showed. 这是因为“错误”的innerHtml总是被替换。因此仅显示最后一个值。

Try below link 尝试下面的链接

Is it possible to append to innerHTML without destroying descendants' event listeners? 是否可以在不破坏后代事件侦听器的情况下附加到innerHTML?

= is the assignment operator. =是赋值运算符。 In your if statements, you must use equal to == or exactly equal to === (checks type also). if语句中,必须使用等于==或完全等于=== (也检查类型)。

You also need to use the add to existing operator += in your statement listing: 您还需要在语句清单中使用添加到现有运算符+=

if(document.getElementById("fullname").value == " "){
    errorMsg[0] = "Please Enter Full Name\n"
}
if(document.getElementById("street").value == " "){
    errorMsg[1]= "Please Enter Street Name\n"
}
if(document.getElementById("postcode").value == " "){
    errorMsg[2]= "Please Enter Postlecode\n"
}
if(document.getElementById("phone").value == " "){
    errorMsg[3]= "Please Enter Phone Number\n"
}
if(document.getElementById("email").value == " "){
    errorMsg[4]= "Please Enter Email Id\n"
}
for(var i=0;i<=errorMsg.length-1;i++){
    document.getElementById("error").innerHTML += "<li>"+errorMsg[i]+"</li>"
}  

I guess you can simply try appending the error message to label in each case. 我想您可以在每种情况下简单地尝试将错误消息附加到标签上。

Inserting in an array will put "undefined" value in an array. 插入数组会将“未定义”的值放在数组中。 eg If you put valid fullname then there won't be anything at errorMsg[0].If you put invalid street, errorMsg[1] will have an entry "Please Enter Street Name\\n". 例如,如果您输入有效的全名,则errorMsg [0]不会有任何内容。如果您输入无效的街道,则errorMsg [1]将具有“请输入街道名称\\ n”条目。

Now,when you are to submit the form, say with submit button you will get error message for invalid street but will get " undefined " for first place of an array. 现在,当您提交表单时,使用“提交”按钮说,您将收到关于无效街道的错误消息,但对于数组的第一位将获得“ undefined ”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM