Change Input Element Type using JavaScript

You can change an input element’s type, from text to password, or hidden to text for example, dynamically using JavaScript.

There are a few reasons why one might need to change the type of an input element dynamically:

  • To have a password box initially display ‘type password here’, but convert to a password element once it takes the focus.
  • To make a hidden form field visible by converting it to a text element, or vice versa.
  • Allow a user to only enter a value once by converting the element to hidden once text has been entered

If you are designing a site that is intended only to run on Mozilla, Safari, or another non-Internet Explorer browser, the following code is sufficient to modify an input element’s type:

<input type="hidden" name="myElement" id="myElement" value="some text" />

<script>
document.getElementById('myElement').type = 'text';
</script>

However, most of us find it necessary to submit to the demands of Internet Explorer.  To meet these demands, we must:

  • dynamically create a new element
  • copy the properties of the old element into the new element
  • set the type of the new element to the new type
  • then replace the old element with the new element

The function below accomplishes the above tasks for you:

<script>
function changeInputType(oldObject, oType) {
  var newObject = document.createElement('input');
  newObject.type = oType;
  if(oldObject.size) newObject.size = oldObject.size;
  if(oldObject.value) newObject.value = oldObject.value;
  if(oldObject.name) newObject.name = oldObject.name;
  if(oldObject.id) newObject.id = oldObject.id;
  if(oldObject.className) newObject.className = oldObject.className;
  oldObject.parentNode.replaceChild(newObject,oldObject);
  return newObject;
}
</script>