简体   繁体   中英

Error messages on contact form

Right now, I'm validating a contact form using java/ajax, and am generating the error messages in javascript with the following

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"
}

which generates

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

I'm not really sure how a label is generated, but I'm wanted to just replace the empty text inputs with the value of the error message when it's not filled out.

I've tried using

fname.value = "the error message";

but that doesn't seem to work. Any ideas on how to get the error message to show up within the input instead of generating a label?

Form markup:

<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>

Use the following JS:

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

I've put together a jsFiddle here: http://jsfiddle.net/dWYWe/ (note that I wrapped messages in a parent object since your snippet implied there was one).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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