Changing type attribute in IE

dinsdag, augustus 26th, 2008 | JavaScript

I never had noticed this before, but a little while ago I found out that changing the type attribute on an input box doesn’t work in Internet Explorer. Not in IE6 and even not in IE7.

I tried element.type="text"; and element.setAttribute("type", "text"); but both methods didn’t work. Strange, because these methods won’t give any problems for setting any other attribute. Sigh.. that Microsoft again…

Fortunately there is a solution. It’s a little dirty and extensive, but hey, it works! The basic idea is that you have to create an new input element and replace it with the old one. The paradox here is that you can set the type attribute for newly created objects with no problems, but editing an existing one give problems. Why? I don’t know. But I’m happy that there’s a solution :-)

Anyway, here’s the code:

function changeInputType(oldObject, oType) {
	var newObject = document.createElement('input');
	newObject.type = oType;
 
	// 'Copy' old types to new element
	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;
 
	// replace old object with new one
	oldObject.parentNode.replaceChild(newObject,oldObject);
	return newObject;
}
Be Sociable, Share!
  • more Changing type attribute in IE

Tags: ,

5 reacties to Changing type attribute in IE

Seblouis
november 21, 2008 at 20:12

Perfect !
Thanks

pablo.chacon.luna
december 3, 2008 at 1:57

it works!
thanks

Mont
april 14, 2009 at 4:23

Have an issue with the new object that is created not being able to .focus()

I am using your function on the onFocus event of some input fields, but the newObject.focus() seems to set focus to the top of the page in IE7.

If the user was not already focussed on the oldObject this wouldn’t be an issue, but as it effectively takes focus away from the field when the “onFocus” its a bit messy.

thoughts ?

Arjan
april 14, 2009 at 11:13

Hi Mont,

I’m not sure if I get your problem right, but what you can do is extend the function with an extra parameter, namely the object who fires this function. It should be something like this:

function changeInputType(currentObject, oldObject, oType) {

…… here the same function

// Add this
if(currentObject == oldObject) {
newObject.focus();
}
else {
currentObject.focus();
}

}

If this is not exactly what you’re looking for or it doesn’t work, please contact me via the contact form.

Good luck!

test03202009
oktober 1, 2009 at 8:29

try newObject.select()

Een reactie plaatsen

About Arjan

Arjan Snaterse Hi, I'm Arjan Snaterse and I'm an SEO consultant and WordPress developer for Uprise, my own company.

Feel free to contact me for any SEO or Wordpress questions.