I have a text input that I'd like to replace with a textarea, preserving all of the attributes. How can I do this with jQuery?
Sample input:
<input type="text" name="newfeature" id="newfeature"
class="form-required" tabindex="3"
aria-required="true" />
Desired output:
<textarea type="text" name="newfeature" id="newfeature"
class="form-required" tabindex="3"
aria-required="true"></textarea>
I know this can be done manually using the .prop()
selector and specifying each attribute/property, but how can I do it dynamically?
Also, this is not necessary, but would it possible to preserve the bindings when doing this?
This also works with the value
attribute correctly:
$('input').each(function() {
var attrs = {};
$.each(this.attributes, function() {
attrs[this.name] = this.value;
});
$(this).replaceWith($('<textarea>').prop(attrs));
});
Example: http://jsfiddle.net/FyYDT/
ADDED
If you want jQuery events to pass along (not recommended), you need to re-bind them. Something like:
$('input').click(function() {
alert('hey');
}).each(function() {
var attrs = {},
ta = $('<textarea>');
$.each(this.attributes, function() {
attrs[this.name] = this.value;
});
$.each($(this).data('events'), function(i, f) {
$.each(f, function(){
ta.bind(i, this.handler);
});
});
$(this).replaceWith(ta.prop(attrs));
});
http://jsfiddle.net/FyYDT/1/
I would simply loop through the input
s attributes:
function makeInputTextarea(inputElem) {
var $textarea = $("<textarea></textarea>");
$.each(inputElem.attributes, function(i, attrib){
var name = attrib.name;
var value = attrib.value;
if(name === "type") return; // textareas don't have a "type" attribute
$textarea.attr(name, value);
});
return $textarea;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With