如何使用jquery将输入元素更改为textarea

时间:2013-06-13 09:08:38

标签: jquery

我有以下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>

现在我想将大小为'100'的每个输入更改为与输入具有相同样式的textarea。

我试过这个:

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

有什么想法吗?


我在答案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);
});

4 个答案:

答案 0 :(得分:5)

jQuery有一个.replaceWith()方法,可以用来将一个元素替换为另一个元素。因此,从输入中复制样式并使用此方法,如下所示:

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

Demo

答案 1 :(得分:3)

尝试一下

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

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

这是一个例子: http://jsfiddle.net/SSwhK/

答案 2 :(得分:1)

试试这个

$("input").each(function(){
      if($(this).attr('size') == "100") {
             my_style = $(this).attr('style');
             $(this).replaceWith("<textarea style='"+my_style+"'></textarea>");
      }
});

答案 3 :(得分:0)

$(document).ready(function(){
    $("input[size=100]").each(function(){
      //how to replace it?
        $(this).after('<textarea style="xxxx"></textarea>').remove();
    });
});

检查http://jsfiddle.net/6JH6B/

相关问题