how to switch between input type="text" and textarea using jquery

11,447

The following should work for you.

var textbox = $("#textbox");
var textarea = $("<textarea id='textarea'></textarea>");
$("#change").click(function () {
    //Check for textbox or textarea
    if ($("#textbox").length === 1) {
        //Copy value to textarea
        textarea.val(textbox.val());
        //Replace textbox with textarea
        textbox = textbox.replaceWith(textarea);
    } else {
        //Copy value to textbox
        textbox.val(textarea.val());
        //Replace textarea with textbox
        textarea = textarea.replaceWith(textbox);
    }
});

You can set the cols and rows in line two in you need to.

jsFiddle

Share:
11,447
Eng Hany Atwa
Author by

Eng Hany Atwa

Updated on June 04, 2022

Comments

  • Eng Hany Atwa
    Eng Hany Atwa almost 2 years

    please help me on this code or another working code that switch between input type="text" and textarea using jquery.

    $(function(){
    $("a#change").toggle(function(){
      var input = document.getElementById('text'),
      textarea  = document.createElement('textarea');
      textarea.id    = input.id;
      textarea.cols  = 40;
      textarea.rows  = 5;
      textarea.value = input.value;
      input.parentNode.replaceChild(textarea,input);
      return false;
    },function(){
      textarea.parentNode.replaceChild(input,textarea);
      return false;
    });
    

    });

    <input type="text" name="text" id="text" /><a href="#" id="change">change</a>