21

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

Samuel Caillerie
  • 8,259
  • 1
  • 27
  • 33
Nagendra Rao
  • 7,016
  • 5
  • 54
  • 92

4 Answers4

27

A more modern way would be to use the URL() constructor and the searchParams property. Let the browser engine do the work!

(new URL(window.location.href)).searchParams.forEach((x, y) =>
    document.getElementById(y).value = x)

Try it online! or on Stack Overflow:

const hash = '?name=some_text&email=more%20text';
const example = "http://example.com/" + hash;

(new URL(example)).searchParams.forEach((x, y) =>
    document.getElementById(y).value = x);
<p>Your name:
<br /><input name="name" id="name" /></p>

<p>Your email:
<br /><input name="email" id="email" /></p>
aloisdg
  • 22,270
  • 6
  • 85
  • 105
  • 2
    Great answer if someone wants to do this to multiple fields (HTML rules doesnt allow same ID), try `document.getElementsByName(y).forEach((p) => (p.value = x)); ` – Rishav Aug 30 '19 at 10:16
  • @Rishav Thank you. In your case you can write `document.getElementsByName(y).forEach(p => p.value = x);` – aloisdg Jan 03 '20 at 13:40
  • Note, if it's a checkbox (`type="checkbox"`), the value attribute shouldn't be changed. Instead the "checked" attribute needs to be set. – K. Frank May 25 '22 at 09:52
  • 1
    Therefore the full lambda expression is: `p => p.type === "checkbox" ? p.checked = (x === "true") : p.value = x` – K. Frank May 25 '22 at 10:12
21

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.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • What if I have an url like this? The hash symbol is inserted at the end of parameters. [https://it-center.am/?description=B16083&amount=AMD40,000&language=hy#modalpayment] Thanks in advance. –  Mar 08 '18 at 20:43
  • Might want to consider the security issues before implementing: https://security.stackexchange.com/questions/29598/should-sensitive-data-ever-be-passed-in-the-query-string – DecimalTurn May 26 '18 at 06:12
  • I know this is a bit old, but when I use this or the answer by alosidg, if I change any field (auto filled or not) all the auto completed fields get cleared. There is other JS on the form (Gmaps auto fill) but this does not happen with the browser auto complete or manually entering the information. – JpaytonWPD Apr 06 '20 at 21:37
  • When you use this answer, does the data get entered when you load the page? If the data disappears after that, that could be the browser’s autocomplete clearing the fields. – Cerbrus Apr 06 '20 at 21:40
  • The data gets entered but as soon as I type a character in a prefilled or empty field it clears and will not come back. No signs of chrome auto complete trying to fill the form. The fields useally highlight when auto complete is filling them in. Plus a dropdown useally shows in the box I am typing in. I am using a userscript to add this function to a 3rd party page. The same thing happens With this answer and the URL() constructor answer below. – JpaytonWPD Apr 08 '20 at 14:46
  • The "working example" link does not exist. – Friedrich -- Слава Україні Aug 02 '21 at 21:19
  • Hey @Cerbrus can you fix the "Working example" link? – Verminous Nov 23 '22 at 21:23
3

Don't bother with JavaScript if you're using PHP.

Just add a little something to the HTML:

<form method="post" action="submit.php" >
  <p>Your name:<br />
  <input name="name" value="<?php echo htmlspecialchars($_GET['name']) ?>" /></p>

  <p>Your email:<br />
  <input name="email" value="<?php echo htmlspecialchars($_GET['email']) ?>"/></p>

  <p>Your message:<br />
  <textarea name="message" id="message" rows="10" cols="50">
    <?php echo htmlspecialchars($_GET['message']) ?>
  </textarea></p>

  <p><input type="submit" value="Send" /></p>
</form>
DefenestrationDay
  • 3,712
  • 2
  • 33
  • 61
1

You can retrieve your current url with window.location.href and then get the default message via a regular expression :

var msg = window.location.href.match(/\?setmessagefield=(.*)/);
document.getElementById("message").value = msg[1];
Samuel Caillerie
  • 8,259
  • 1
  • 27
  • 33
  • 1
    Have you try to see what are in these variables : `console.log(window.location.href)` should give you `www.xyz.com/contact.html?setmessagefield=some_text` and `console.log(msg)` should give you the array : `["?setmessagefield=some_text", "some_text"]`. – Samuel Caillerie Dec 29 '12 at 08:07