Skip to content

Instantly share code, notes, and snippets.

@pfiaux
Forked from bminer/changeTypeAttr.js
Created September 20, 2012 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pfiaux/3755288 to your computer and use it in GitHub Desktop.
Save pfiaux/3755288 to your computer and use it in GitHub Desktop.
Cross-browser solution to change the 'type' attribute of an `<input/>` tag. Edited to work in Drupal.
/* id is the id tag of <input/> element
type is the type you want to change it to.
jQuery is required and assumed to be the jQuery variable */
function changeType(id, type) {
var x = jQuery("#"+id);
if(x.attr('type') == type)
return x; //That was easy.
try {
return x.attr('type', type); //Stupid IE security will not allow this
} catch(e) {
//Try re-creating the element (yep... this sucks)
//jQuery has no html() method for the element, so we have to put into a div first
var html = jQuery("<div>").append(x.clone()).html();
var regex = /type=(\")?([^\"\s]+)(\")?/; //matches type=text or type="text"
//If no match, we add the type attribute to the end; otherwise, we replace
var tmp = jQuery(html.match(regex) == null ?
html.replace(">", ' type="' + type + '">') :
html.replace(regex, 'type="' + type + '"') );
//Copy data from old element
tmp.data('type', x.data('type') );
var events = x.data('events');
var cb = function(events) {
return function() {
//Bind all prior events
for(i in events)
{
var y = events[i];
for(j in y)
tmp.bind(i, y[j].handler);
}
}
}(events);
x.replaceWith(tmp);
setTimeout(cb, 10); //Wait a bit to call function
return tmp;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment