views:

39

answers:

2

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

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

For the record the following does not work:

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

Neither does this work:

var field = document.getElementsByTagName("input")[0];
field.setAttribute("type", "hidden");
+1  A: 

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

letronje
Nope doesn't work!
corydoras
+3  A: 

The indication when researching this is that IE does not let you do this.

This article explains what you shoudl do to achieve a similar effect:

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

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 code is also reproduced by this site, so thought I'd let you visit it for the benefit of page hits for them.

I would be interested as to what is different about IE from the other browsers that causes issues with this.

Also, anyone care to try it on IE9?

James Wiseman
Man IE is crazy!
Jacob
Thanks, that does the trick!
corydoras
No worries. Do you want to accept that then :-)
James Wiseman