Eng Hany Atwa
Eng Hany Atwa

Reputation: 323

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

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>

Upvotes: 3

Views: 12236

Answers (1)

Dracs
Dracs

Reputation: 457

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

Upvotes: 4

Related Questions