将函数值传递给innerhtml div中的输出

时间:2013-10-15 05:58:06

标签: javascript html

嗨,大家好我试图将验证函数的返回值传递给文档的html部分中的innerhtml。由于某种原因没有工作......任何帮助表示赞赏。

function validate(form) {
    fail  = validateName(form.name.value)
    fail += validateEmail(form.email.value)
    fail += validateCity(form.city.value)
    if (fail == "") return true
    else { alert(return document.getElementById('#errors').innerHTML=fail;}); return false}
    }

    function validateName(field) {
        if (field == "") return "No name was entered.\n"
        else if (field.length < 3) return "Name must be at least 3 characters.\n"
        else if (!/[a-zA-Z ]*$/.test(field)) return "Name can only have alphabetical characters.\n"
        return ""
        }
    function validateEmail(field) {
        if (field == "") return "No email was entered.\n"
        else if (!((field.indexOf(".") > 0) && (field.indexOf("@") > 0)) || /[^a-zA-Z0-9.@_-]/.test(field)) return "The email address is invalid.\n"
        return ""
        }
    function validateCity(field) {
        if (field == "") return "No city was entered.\n"
        else if (field.length < 3) return "City must be at least 3 characters.\n"
        else if (!/[a-zA-Z ]*$/.test(field)) return "City can only have alphabetical characters.\n"
        return ""
        }



  <form action="<?php echo $editFormAction; ?>" name="subscribe" onSubmit="return validate(this)" id="subscribe" method="POST">
<div id="errors"></div>
<input name="name" autocomplete="off" required pattern="[a-zA-Z ]*$" title="Please enter only alphabetic characters" type="text" id="name" placeholder="Your name"/>


<input name="email" autocomplete="off" required id="email" type="email" title="Please enter your email address" placeholder="Your email address"/>

<input name="city" autocomplete="off" required pattern="[a-zA-Z ]*$" title="Please enter only alphabetic characters" id="city" placeholder="Your city"/>

<section id="buttons">
            <input type="reset" name="reset" id="resetbtn" class="resetbtn" value="Reset">

            <input type="submit" name="submit" id="submitbtn" class="submitbtn" tabindex="7" value="Submit this!">

            <br style="clear:both;">
        </section>

2 个答案:

答案 0 :(得分:0)

使用错误代替 #errors ,并从return删除alert

if (fail == "") return true;
else { 
   //use innerText in place of innerHTML if #errors is not a div
   document.getElementById('errors').innerHTML=fail; use errors in place of #errors
   alert(fail);
   return false
}

答案 1 :(得分:0)

对于道德编码,您可能需要避免在函数或方法的参数内返回函数的值:

注意这一行:

else { alert(return document.getElementById('#errors').innerHTML=fail;}); 

return 作为 alert() ....参数的一部分传递,似乎不合适!

这会导致Syntax Errors