Rough Book

random musings of just another computer nerd

jQuery tip: Changing the TYPE attribute of an INPUT element

I was trying to change the type attribute (using jQuery) of an input element from submit to button when I got this error:

type property can’t be changed

Apparently, you can’t change the type attribute of an input element once it’s part of the DOM. I figured out a way to do it by cloning the old element and then changing its attribute. Since the element isn’t part of the DOM, you can change its attribute. After that, you can add it to the DOM and remove the old element:

var oldButton = jQuery("#Submit");
    var newButton = oldButton.clone();

    newButton.attr("type", "button");
    newButton.attr("id", "newSubmit");
    newButton.insertBefore(oldButton);
    oldButton.remove();
    newButton.attr("id", "Submit");

Popularity: 39% [?]

May 26, 2009 Posted by | Programming and Development, Web | , , , | 17 Comments

   

All original content on these pages is fingerprinted and certified by Digiprove