联系表单上的错误消息

时间:2013-07-23 21:19:20

标签: javascript validation

现在,我正在使用java / ajax验证联系表单,并使用以下内容在javascript中生成错误消息

messages: 
{
    fname: "Please fill in your name",
    email: "Your email will help us contact you",
    subject: "Please fill in the subject of your message",
    recipient: "Please let us know who you would like to contact",
    message: "Please fill out your message",
    captcha: "Please answer 2x3"
}

生成

<label class="error">The error message for this id</label>

我不确定标签是如何生成的,但是我想在没有填写错误消息的情况下将空文本输入替换为错误消息的值。

我尝试过使用

fname.value = "the error message";

但这似乎不起作用。有关如何在输入中显示错误消息而不是生成标签的任何想法?

表单标记:

<form name="myform" id="myform" action="" method="post">
    <fieldset>
        <label for="fname" id="name_label">First Name</label> 
        <input type="text" name="fname" id="fname" value=""> 
        <label for="lname" id="lname_label">Last Name</label> 
        <input type="text" name="lname" id="lname" value="">
    </fieldset>
    <fieldset>
        <label for="email" id="email_label">Email</label> 
        <input type="text" name="email" id="email" value=""> 
        <label for="phone" id="phone_label">Phone Number</label> 
        <input type="phone" name="phone" id="phone" value="">
    </fieldset>
    <fieldset>
        <label for="message" id="message_label">Message</label> 
        <textarea name="message" id="message" size="30" value=""></textarea> 
        <label for="captcha" id="captcha_label">What's 2x3?</label> 
        <input type="text" name="captcha" id="captcha" value="">
    </fieldset><
    input type="submit" name="submit" value="Submit">
</form>
<p>
    <img src="%3C?php%20echo%20get_template_directory_uri();%20?%3E/images/loader.gif" id="loading" alt="Loader" name="loading">
</p>
<div id="results"></div>

1 个答案:

答案 0 :(得分:1)

使用以下JS:

document.myform.fname.value = messages_parent_obj.messages.fname;

我在这里整理了一个jsFiddle:http://jsfiddle.net/dWYWe/(请注意,我将messages包装在父对象中,因为您的代码段暗示有一个)。