Autofilling forms with Javascript

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.

[codepen_embed height=”265″ theme_id=”0″ slug_hash=”ybxBqN” default_tab=”result” user=”benalexkeen”]See the Pen ybxBqN by Ben (@benalexkeen) on CodePen.[/codepen_embed]

Let’s start with our html form:


<a href="#" onClick="autoFill(); return true;" >Click to Autofill</a>
<form>
  <p>
    <label>Text Input: </label>
    <input type="text" id="input1">
  </p>
  <p>
    <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>
    </select>
  </p>
  <p>
    <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
  </p>
</form>

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;
      }
    }
  }
</script>