Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change an input element to textarea using jquery [duplicate]

Tags:

jquery

I have the following html:

<div>
    <input type="text" style="xxxx" size="40"/>
    <input type="text" style="xxxx" size="100"/>
    <input type="text" style="xxxx" size="100"/>
    <input type="text" style="xxxx" size="40"/>
</div>

Now I want to change each input whose size is '100' to a textarea which has the same style as the input.

I have tried this:

$("input[size=100]").each(function(){
  //how to replace it?
});

Any ideas?


I used this solution found in the answers here:

$("input[size=100]").each(function() {
    var style = $(this).attr('style'), textbox = $(document.createElement('textarea')).attr({
        id : $(this).id,
        name : $(this).name,
        value : $(this).val(),
        style : $(this).attr("style"),
        "class" : $(this).attr("class"),
        rows : 6
    }).width($(this).width());
    $(this).replaceWith(textbox);
});
like image 873
hguser Avatar asked Jun 13 '13 09:06

hguser


3 Answers

jQuery has a .replaceWith() method you can use to replace one element with another. So, copy your styles from the input and use this method, as follows:

$('input[size="100"]').each(function () {
    var style = $(this).attr('style'),
        textbox = $(document.createElement('textarea')).attr('style', style);
    $(this).replaceWith(textbox);
});

Demo

like image 60
Derek Henderson Avatar answered Nov 05 '22 16:11

Derek Henderson


Try something along the lines of

$('input[size="100"]').each(function()
{
    var textarea = $(document.createElement('textarea'));
    textarea.text($(this).val());

    $(this).after(textarea).remove();
});

Here's an example: http://jsfiddle.net/SSwhK/

like image 36
MisterBla Avatar answered Nov 05 '22 16:11

MisterBla


Try like this

$("input").each(function(){
      if($(this).attr('size') == "100") {
             my_style = $(this).attr('style');
             $(this).replaceWith("<textarea style='"+my_style+"'></textarea>");
      }
});
like image 1
Gautam3164 Avatar answered Nov 05 '22 17:11

Gautam3164