Pre-fill forms in development

Posted: 07/05/2009

Automated testing is great, but I often want to click through the many pages of my application myself, without slowing down to fill in form data. I use three javascript functions to provide a simple way for me to pre-fill form data. Say I have an order form that takes a first name, last name, and credit card type. Like this:

  <form>
    <input name="order[first_name]" type="text">
    <input name="order[last_name]" type="text">
    <select name="order[card_type]">
      <option value="visa">Visa</option>
      <option value="american_express">American Express</option>
    </select>
  ...
  </form>

I could write a javascript file that I only include in my development environment that would look like this:

  fill('order[first_name]', "Lou");
  fill('order[last_name]', "Zell");
  select('order[card_type]', "American Express");

The javascript functions that enable me to do this:

function find(name){
  n = document.forms.length
  for (var i=0; i < n; i++){
    k = document.forms[i].elements.length
    for(var j=0; j < k; j++){
      if(document.forms[i].elements[j].name == name){
        return(document.forms[i].elements[j])
      }
    }
  }
}
  
function fill(name, content){
  find(name).value = content;
}
  
function select(name, content){
  s = find(name)
  for (var i = 0; i < s.options.length; i++){
    if (s.options[i].innerHTML == content){
      s.selectedIndex = i;
      return;
    }
  }
}

These functions don’t rely on any library, and they also shouldn’t be used in production because they are far from optimized. Yes, I am 100% sure there is a much more efficient way to write them, but they work just fine for what I need them to do.

If you want to get fancy pants you could create different sets of data to fill a form with, and attach each fill function to a link’s click event. Something like:

  <a id="fill_with_bob">fill with bob's info</a>
  <a id="fill_with_jane">fill with jane's info</a>

  $('#fill_with_bob').click(function(){
    fill('order[first_name]', "Bob");
    fill('order[last_name]', "Jones");
    select('order[card_type]', "American Express");
  });
    
  $('#fill_with_jane').click(function(){
    fill('order[first_name]', "Jane");
    fill('order[last_name]', "Jones");
    select('order[card_type]', "Visa");
  });

I used jquery for that last part. And it’s not tested.

About Me

I'm a skier, web developer, entrepreneur, freelancer, and all around stand-up guy living in Manhattan. This is me, repping one of my favorite shirts...

Follow me on twitter or send me an email.

All Posts

Music Blogs