Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Bookmarklet to autofill forms (URL and TITLE of page you're on when you click the bookmarklet)

BOOKMARKLETS TO AUTO FILL FORMS

I wanted to create a bookmarklet that would find the user's URL and title of the page they were on when they clicked the bookmarklet, go to my website's create new link form, and autofill the fields with that information. While researching, I found that nothing I could find fit this description, so I cobbled the code together from a few different sources.

FIRST, create a link to the bookmarklet, which you will tell people to drag to their browser bookmark bar. This will also take in the website and decode it so it shows up as http:// in the form. Make sure you match the name of your fields in your form that you want to be autofilled.

<a href="javascript:(function(){var newURI='YOUR_URL_TO_YOUR_FORM_PAGE?NAME_OF_URL_FIELD='+encodeURIComponent(decodeURIComponent(window.location.href))+'&NAME_OF_TITLE_FIELD='+encodeURIComponent(document.title.replace('%20',' ')); window.location.href=newURI;})();">TEXT THAT THE BOOKMARKLET WILL SAY WHEN YOU DRAG IT TO YOUR BOOKMARK BAR</a>

NEXT, you need this jquery code in the header tag on your form page, which takes the information in the URL and splits it. I modified this jquery code from http://lightignite.com/help-your-customers-fill-out-web-forms-with-url-query-strings to add a decode component into the title field so it will recognize %20 as a space when autofilling.

<script>
  $(function () {
    
    //grab the entire query string
    var query = document.location.search.replace('?', '');
    
    //extract each field/value pair
    query = query.split('&');
    
    //run through each pair
    for (var i = 0; i < query.length; i++) {
    
      //split up the field/value pair into an array
      var field = query[i].split("=");
      
      //target the field and assign its value
      $("input[name='" + field[0] + "'], select[name='" + field[0] + "']").val(decodeURIComponent(field[1]));
    
    }
  });
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment