Hiding a text field in a form using javascript

What is the correct way to hide an input text box? The following will appear: work in all browsers except Internet Explorer. I am testing IE8.

var field = document.getElementsByTagName("input")[0]; field.type = 'hidden'; 

For recording, the following does not work:

 var field = document.getElementsByTagName("input")[0]; field.style.display = 'none'; 

Also this does not work:

 var field = document.getElementsByTagName("input")[0]; field.setAttribute("type", "hidden"); 
+4
source share
2 answers

An indication when exploring this is that IE does not allow you to do this.

This article explains what you are doing to achieve a similar effect:

http://www.universalwebservices.net/web-programming-resources/javascript/change-input-element-type-using-javascript

However, most of us consider it necessary to comply with the requirements of the Internet Explorer. To meet these requirements, we need:

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

The code is also reproduced on this site, so I thought I would let you visit it for the benefit of page hits for them.

I would be interested to know what sets IE apart from other browsers that cause problems with this.

Also, does anyone want to try it on IE9?

+4
source

I wonder why style.display='none' does not work. Have you tried style.visibility = 'hidden' ?

+1
source

All Articles