简体   繁体   中英

Using jQuery to read from .serialize to populate a form

First off, I'm a but of a JS newbie. I have form1 asking for a user's email address which I am serializing. What I need is to take this single field of data and unserialize it in a field in a more complex form2 which is spawned in a lightbox when a user submits the form1.

I have the serialization done, and the lightbox done, but I can't figure out how to grab the email address submitted in form1 and pre-populate the email field in form2 with that data. Any help would be appreciated.

Code for the two forms is below. (leaving out lightbox as it doesn't apply). Basically, I need to get the 'email' from 'form1' into the 'email' field in 'form2'

<form action="#" id="form1">
   <label>email:</label> <input type="text" name="email" id="email"/> 
    <input type="submit" value="send" name="submit" />
</form>

<form action="#" id="form2">
   <label>Email:</label> <input type="text" name="email" id="email"/>
   <label>Zip Code:</label> <input type="text" name="zip" id="zip"/>
   <strong>Choose a Newsletter </strong>
   <ul><li><input type="checkbox" value="2" name="Weekly" id="Weekly"><label>Weekly</label></li>
<li><input type="checkbox" value="4" name="Daily" id="Daily"><label>Daily</label></li>
<li><input type="checkbox" value="8" name="Monthly" id="Monthly"><label>Monthly</label></li>
</ul>
<input type="submit" value="Subscribe" name="Subscribe" />
</form>

I could help a little more if you showed more code, but this is essentially what you need to do.

You have the value of email in both its raw and serialized form. Since form2 is in a lightbox, it is really on the same page. So, you can easily change the value of the email field within form2 .

You would do this with the .val() jQuery function like so: $("#form2 #email").val(email);

Now obviously you're going to need to substitute out the jQuery selector ( #form2 #email ) to something that actually fits the new email field in form2 . You will also need to change email within the .val() function to be whichever variable you assigned as the email address from form1 .

EDIT

With the addition of your code, I am able to offer a little bit more - thanks!

This code will run when you submit the first form and will place the value of form1's email into form2.

$("#form1").submit(function(sent){

    // Sets the value of emailvalue to the current email address
    var emailValue = $("#form1 #email").val();
    // Places the value of emailValue into the email field in form2
    $("#form2 #email").val(emailValue);

});

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