I often want to click through the many pages of my application without slowing down to fill in form data. To do this, I use javascript to pre-fill forms with a click. 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.
You could even 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>
And the javascript:
$('#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.