Randomblue
Randomblue

Reputation: 116273

Changing the type of an input element

I have an input type="text" that I want converted to an input type="button". I have tried attr(), but that does not work:

HTML:

<input type="text"></input>

JavaScript:

$('input').attr('type', 'button');

What's wrong?

Upvotes: 2

Views: 202

Answers (2)

James Allardice
James Allardice

Reputation: 165971

You can't change the type attribute with jQuery. This is from the jQuery source:

// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
    jQuery.error( "type property can't be changed" );
}

The reason, according to the comment, is that it causes problems in IE. Since jQuery is designed to reduce complications that arise due to differences between browsers, it would go against that idea if it worked in other browsers. I'm assuming that's why the jQuery team have simply removed that ability.

As has already been mentioned, your best option will probably be to replace the input element in question with a new one.

Upvotes: 6

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

This is partially covered in the documentation:

Note: Internet Explorer does not allow you to change the type attribute of an <input> or <button> element.

That you are prevented from even attempting this in any browser comes from the jQuery source:

// We can't allow the type property to be changed (since it causes problems in IE)
if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
    throw "type property can't be changed";

(Looks like the docs need updating.)

Upvotes: 0

Related Questions