DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • What Is React? A Complete Guide
  • Reactive Programming
  • Best Practices for Securing Infrastructure as Code (Iac) In the DevOps SDLC
  • Authorization: Get It Done Right, Get It Done Early

Trending

  • What Is React? A Complete Guide
  • Reactive Programming
  • Best Practices for Securing Infrastructure as Code (Iac) In the DevOps SDLC
  • Authorization: Get It Done Right, Get It Done Early
  1. DZone
  2. Coding
  3. Languages
  4. Pre-filling Forms via Custom Bookmarklet- A CSS solution worth embracing

Pre-filling Forms via Custom Bookmarklet- A CSS solution worth embracing

Sarah Parker user avatar by
Sarah Parker
·
Jul. 22, 14 · Interview
Like (0)
Save
Tweet
Share
5.77K Views

Join the DZone community and get the full member experience.

Join For Free

Testing has always been and will continue to remain the number one priority of web developers engaged in the execution of different types of web development projects. Whether it's about performing manual testing or automated testing, web developers don't delay in spending a good duration of time on ensuring that the site renders a brilliant user experience. Unit and integration testing are great, provided you're able to pin-point the bugs in your site's code. Testing webpage forms can be tedious task. Irrespective of whether you're a novice or a proficient web developer, there might be situations when testing web page forms may give you jitters. Hence, as an attempt to combat all your worries, I've written this blog to make you familiar with an excellent solution to this problem. Here, I've discussed about building a JavaScript bookmarklet for pre-filling forms placed on different web pages. Do note that since there will be a need to insert random data for most of the fields, I'll be using a great library called Faker. This library will be used for generating fake names, addresses and phone numbers.

Step 1- Building the JavaScript Bookmarklet

Well, you can easily build and distribute a JavaScript bookmarklet by simply creatinga Pen on CodePen and adding the below mentioned snippet into an href:


 <a href="javascript: **js goes here** "></a>

In my example, I'll be using jQuery for keeping the code lean and cross-browser compatible. Now, in order to prevent the updation of the actual bookmarklet, you can start updating the snippet code via an external file as explained below:

<a href="javascript:
(function(d) {
  var body = d.getElementsByTagName('body')[0],
  script = d.createElement('script');
  script.src = '//localhost.com/pathtomyfile.js';
  body.appendChild(script);
}(window.document));
">My Javascript Bookmarklet</a>


Step 2- Load a preferred script file into the bookmarklet

Now that you've the bookmarklet ready with you, it's time to load a script file that suits your purpose. Here, it is absolutely essential to ensure that the code doesn't conflict the original page in any manner. Here's how the script file needs to be loaded into the created JavaScript bookmarklet:

(function(win, doc, $, undefined) {
  'use strict';
   
  // Don't run if jQuery isn't loaded
  if (typeof window.jQuery === 'undefined') {
  return;
  }
  
  // Our code will go here.

  }(window, window.document, window.jQuery));
In addition to above, use the below mentioned code for generating random numbers:
var _rand = function(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}


The final loading of FakerJS script is being performed using $.getScript as explained below:

$.getScript('//cdnjs.cloudflare.com/ajax/libs/Faker/0.7.2/MinFaker.js')
  .done(function() {
  // run our functions from here
  })
  .fail(function() {
  win.console.error('ERROR: FakerJS not loaded!');
  });


For the above code, do note that Faker provides a quick access to fake names, emails, addresses etc.

Step 3- Creating a constructor function

As per this step, you'll need to create a constructor function that can be used for loading the data that can be re-used as and when required in the future. Here's how it will be done:

 var FormData = function(faker) {
  this.faker  = faker;
   
  this.randomWord = faker.Internet.domainWord();

  this.username  = 'fake_' + this.randomWord;
  this.username  += _rand(100,9999);

  // set this value to your password specifications
  this.password  = 'pass1234';

  this.name  = faker.Name.findName();

  this.address1  = faker.Address.streetAddress();
  this.city  = faker.Address.city();
  this.state  = faker.random.br_state_abbr();
  this.zip  = faker.Address.zipCode();

  // Chris' actual credit card number
  this.cc  = '4242 4242 4242 4242';
  this.exp1  = _rand(1,12);
  this.exp2  = _rand(14,22);
  this.cvv  = _rand(100,999);

};

Step 4- Setting the status of certain file types to 'Random'

Here, you'll be able to set the status of specific field types such as checkboxes and select boxes as 'Random'. For this, you simply need to extend the FormData object with some functions as explained below:

// Randomly select dropdown

 FormData.prototype.randomizeSelect = function(el) {
  var $el  = $(el),
  len  = $el.find('option').length - 1;

  $el.children('option')
  .prop('selected', false)
  .eq( _rand( 1,len + 1 ) )
  .prop('selected', true);
  };

  // Randomly select radio button
  FormData.prototype.randomizeRadio = function(radios) {
  radios  = radios.not('[type="hidden"]');
  var len = radios.length;

  radios
  .prop('checked', false)
  .eq( _rand( 0, len - 1 ) )
  .prop('checked', true);
  };

  // Add some lorem text for textareas
  FormData.prototype.randomizeParagraph = function(el) {
  $(el).val(this.faker.Lorem.sentence(5));
  };

  // Randomize all checkbox fields
  FormData.prototype.randomizeCheckbox = function(el) {
  var $el  = $(el);

  $el.prop('checked', false);

  if (_rand( 0,1 ) === 0) {
  $el.prop('checked', true);
  }
  };

  FormData.prototype.randomizeEmail = function(el) {
  // if we want different emails for all email fields, we can modify this
  $(el).val('chriscoyier+' + this.randomWord + '@gmail.com');
  };


Step 5- Bind the data to form fields

As per this last step, you'll be binding data to the fields available on the form. For this, you can use jQuery to grab fields or field types and replace their value without a data object. The coding involved for this is being mentioned below:

var fillForm = function() {
  data = new FormData(window.Faker);

  $('#name').val(data.name);
  $('#username').val(data.username);
  $('#cc').val(data.cc);
  $('#exp-1').val(data.exp1);
  $('#exp-2').val(data.exp2);
  $('#cvv').val(data.cvv);
  $('#address').val(data.address1);
  $('#city').val(data.city);
  $('#state').val(data.state);
  $('#zip').val(data.zip);
  $('#pw').val(data.password);
  $('#pw-repeat').val(data.password);

  data.randomizeRadio($('[name="radio-choice"]'));

  // Randomize all select boxes

  $('select').each(function() {
  data.randomizeSelect(this);
  });

  // Randomize all checkboxes
  $('input[type="checkbox"').each(function() {
  data.randomizeCheckbox(this);
  });

  // Randomize all textareas
  $('textarea').each(function() {
  data.randomizeParagraph(this);
  });
   
  // Randomize all emails
  $('input[type="email"').each(function() {
  data.randomizeEmail(this);
  });
   
  };

Wrapping Up

With that, it's a wrap on this blog. Hope you'd have enjoyed going through the steps and found them interesting too. With a custom javascript bookmarklet, you can actually fill the forms with quick and random data.
Bookmarklet Form (document) CSS

Opinions expressed by DZone contributors are their own.

Trending

  • What Is React? A Complete Guide
  • Reactive Programming
  • Best Practices for Securing Infrastructure as Code (Iac) In the DevOps SDLC
  • Authorization: Get It Done Right, Get It Done Early

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: