Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

javascript - Pre-fill form field via URL in html

I am looking for a simple way to pre-fill a field in my contact form when ever a user clicks on a link that is given in some other page.

This is my contact form in html :

<form method="post" action="submit.php" >
    <p>Your name:
    <br /><input name="name" /></p>
    <p>Your email:
    <br /><input name="email" /></p>
    <p>Your message:
    <br /><textarea name="message" id="message" rows="10" cols="50"></textarea></p>
    <p><input type="submit" value="Send" /></p>
</form>

I want to fill the "message" field with "some text" when a user clicks on a url like www.xyz.com/contact.html?setmessagefield=some_text

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

JavaScript has no built-in functions to parse url parameters like that (Since those GET parameters are usually used to send data to the server).
I'd suggest using a hash instead (A hash is purely client-side):

www.xyz.com/contact.html#name=some_text&email=more%20text

Now, add some id's to your fields:

<p>Your name:
<br /><input name="name" id="name" /></p>

<p>Your email:
<br /><input name="email" id="email" /></p>

Then set the values like this, on load:

var hashParams = window.location.hash.substr(1).split('&'); // substr(1) to remove the `#`
for(var i = 0; i < hashParams.length; i++){
    var p = hashParams[i].split('=');
    document.getElementById(p[0]).value = decodeURIComponent(p[1]);;
}

Working example

The big advantage of this is that it's flexible. If you want to set the values of 2 fields, you supply those 2 fields' id's in the hash:

www.xyz.com/contact.html#name=some_text&email=more%20text

4 fields? 4 id's:

www.xyz.com/contact.html#name=some_text&email=more%20text&username=john&age=23

No need to edit the code, then.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...