How can I replace input with a text area that preserves all attributes using jQuery?

I have a text input that I would like to replace with a text field while retaining all the attributes. How can I do this using jQuery?

Input Example:

<input type="text" name="newfeature" id="newfeature" class="form-required" tabindex="3" aria-required="true" /> 

Required Conclusion:

 <textarea type="text" name="newfeature" id="newfeature" class="form-required" tabindex="3" aria-required="true"></textarea> 

I know that this can be done manually using the .prop() selector and specifying each attribute / property, but how can I do this dynamically?

In addition, this is optional, but is it possible to maintain the bindings at the same time?

+4
source share
3 answers

This also works correctly with the value attribute:

 $('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 go through (not recommended), you need to relink them. Sort of:

 $('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/

+4
source

I would just skip the input 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; } 
+1
source
 $(function() { $('input[type="text"]').parent().each(function({ $(this).html($(this).html().replace(/(<\/)input/gi, "$1textarea").replace(/(<textarea[^>]*)value\=['"](.*)['"]([^>]*)\/>/, "$1>$2</textarea>")); })); }); 

Gotta do the trick?

You can do

 $('input, textarea').live('click', function() { // do actions! }); 

To save the bindings

0
source

Source: https://habr.com/ru/post/1399578/


All Articles