Gheorghita Sorin

Web Developer and Designer

Autocomplete a form field by clicking a link

Let’s say you have a product presentation website and for each product you need  have an “Enquiry” button who redirects the user to a form which will be completed and then sent to your email address. Autocomplete forms comein handy.

A common problem is that most of the users forget to complete the subject with the name of the product they are interested. Most of them will put on the subject line “Product enquiry”.

So, you need to automatically complete the subject field (for example) with the name of the product, or whatever you need to be representative.

So, you can autocomplete a form field using a custom link for each product and a little javascript code.

For example you have the domain : mywebsite .com and the form is on page “enquiry”.

  1. The link for a button who autocompletes the subject field will be: mywebsite .com/enquiry#subject=whatever_you_want_here
    Please see the image below for more explanations.
    autocomplete-a-form-field-using-a-link
  2.  After creating your links using the method above, you will need to insert a javascript into the head or footer of your website.

<script type=”text/javascript”>// <![CDATA[
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]);;
}
// ]]>
</script>

And this is pretty much it. If there are more fields that you need to be completed, use the “&” character to add another field name and text after.
For example: mywebsite .com/enquiry#subject=whatever_you_want_here&mail=whatever_you_want_here

If you need more details and explanations, please write in a comment below.

Next Post

Previous Post

© 2019 Gheorghita Sorin

Theme by Anders Norén