Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace an input with a textarea preserving all attributes using jQuery?

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?

like image 602
cwd Avatar asked Mar 03 '12 20:03

cwd


2 Answers

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/

like image 134
David Hellsing Avatar answered Sep 20 '22 21:09

David Hellsing


I would simply loop through the inputs 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;
}
like image 37
Luca Matteis Avatar answered Sep 21 '22 21:09

Luca Matteis