Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - Duplicate Field Input Text In Real Time

I'm trying to figure out how to copy a users text input in one form field to another. Specifically, when someone fills in their email address in the contact form, it will be duplicated in the mailing list form.

Both these forms are using ajax so there's no concerns about the input text being lost on submit.

This is the code I have:

    <div id="contact_form">
          <form name="contact" method="post" action="">

            <input type="text" name="name" id="name" size="30" value="Name" class="text-input" />
            <label class="error" for="name" id="name_error">Please enter your name.</label>
            <br />

            <input type="text" name="email" id="email" size="30" value="Email" class="text-input" />
            <label class="error" for="email" id="email_error">I need your email.</label>
            <br />

            <textarea rows="10" cols="30" type="textarea" name="message" id="message" value="Message" class="text-input" ></textarea>
            <label class="error" for="message" id="message_error">A message is required.</label>

            <br />
            <input type="submit" name="submit" class="button" id="submit" value="Send" />

          </form>
</div>

<div id="details">
    <p>some details here, not sure what yet</p>
    </div>

<div id="mail_list">
    <input type="text" id="mail" value="Your email" name="mail_list" /><input type="submit" name="submit" class="button" id="submit" value="Send" />
    </div>

I found this in the Jquery documentation, but couldn't get it to work:

$("#email").optionCopyTo("#mail");

Thanks!

like image 993
logic-unit Avatar asked Oct 31 '10 01:10

logic-unit


2 Answers

You said you want it in real time. I assume that means while the user is typing, the value should be replicated for each keystroke.

If that's right, try this:

var mail = document.getElementById("mail");

$("#email").keyup(function() {
    mail.value = this.value;
});

Or if you want more jQuery:

var $mail = $("#mail");

$("#email").keyup(function() {
    $mail.val( this.value );
});

This will update for each keyup event.

I'd probably add a redundant blur event in case there's an autocomplete in the field.

$("#email").blur(function() {
    $mail.val( this.value );
});
like image 93
user113716 Avatar answered Sep 19 '22 17:09

user113716


Since all your fields have unique ids, this is quite straight forward:

$(function() {                                       // <== Doc Ready
    $("#email").change(function() {                  // When the email is changed
        $('#mail').val(this.value);                  // copy it over to the mail
    });
});

Try it out with this jsFiddle


.change()
.val()

like image 45
Peter Ajtai Avatar answered Sep 19 '22 17:09

Peter Ajtai