In this post we’re going to write some JavaScript that will allow us to autofill a form. We’ll fill in a text input, a dropdown input and a radio input. See the result in the Codepen example below.

See the Pen ybxBqN by Ben (@benalexkeen) on CodePen.0

Let’s start with our html form:

<a href="#" onClick="autoFill(); return true;" >Click to Autofill</a>
    <label>Text Input: </label>
    <input type="text" id="input1">
    <label>Dropdown Input: </label>
    <select id="input2">
      <option value="Dropdown1">First Option</option>
      <option value="Dropdown2">Second Option</option>
      <option value="Dropdown3">Third Option</option>
    <label>Radio Input: </label>
       <input type="radio" name="input3" value="Radio1">First Radio
       <input type="radio" name="input3" value="Radio2">Second Radio
       <input type="radio" name="input3" value="Radio3">Third Radio

Now, we’re going to autofill this form with some text in our text input “My Text Input”. We’ll choose the second dropdown item and we’ll choose the third radio button.

<script type="text/javascript">
  function autoFill() {
    document.getElementById('input1').value = "My Text Input";
    document.getElementById('input2').value = "Dropdown2";
    var radioElements = document.getElementsByName("input3");

    for (var i=0; i<radioElements.length; i++) {
      if (radioElements[i].getAttribute('value') == 'Radio3') {
        radioElements[i].checked = true;