create textarea with Javascript

jvcoach23

Centurion
Joined
May 22, 2003
Messages
192
Location
Saybrook, IL
i have an asp.net site. I'd like to be able to create a textarea with javascript. I don't want to use a post back.

does anyone have a code snibit they can share. i've found a couple on the net, but haven't been able to get them to work. what kind of plumbing needs to be in place so that the textareas show up in the correct spot. do i need to put it in a table, or can i have a div tag and add it inside the div tag. not real handy with javascript, so if you have code example that would be great.

thanks
shannon
 
I'm not sure if you can dynamically create a textarea; however, if you have the textarea in a div tag you can dynamically set it's visible property (style="display:none;" iirc) like this:

Visit this page to determine which value for "display" you want to set when you make your item visible.

Imagine this is your web page
[highlight=html4strict]
<html>
<body>
<div id="textareaID" style="display:none;">
<input type="textarea" name="txtarea" />
</div>
<br />
<br />
<input type="submit" onclick="ToggleTextArea()" />
</body>
</html>
[/highlight]

Add this javascript to your page
[highlight=javascript]
<script type="text/javascript">
function ToggleTextArea()
{
if(document.getElementById("textareaID").style.display == "none")
{
// element is not visible so make it "block" visible
document.getElementById("textareaID").style.display = "block";
}
else
{
// the element is visible so make it "none" visible
document.getElementById("textareaID").style.display = "none";
}
}
<script>
[/highlight]


If you have .NET 2.0 and the Ajax Toolkit or .NET 3.5 which has it built in you can place the textarea in an <asp:UpdatePanel /> tag and then while the page does do a post back, it will not visibly redraw your entire page for the user. Thats called a Partial Page Refresh -- a staple of Ajax Development.

HTH
 
I'd like to prepend this post by saying that JavaScript is the $_hit, and in my opinion the most underrated language.


Code:
<html>
<head>
<script type="text/javascript">
function AddTextAreaDOM()
{
   var area = document.createElement('textarea'); 
   document.getElementById('placeholder').appendChild(area);
}

function AddTextAreaString()
{
  var div = document.getElementById('placeholder');
  div.innerHTML += "<textarea />";
}
</script>
<body>
<div id="placeholder">
</div>
<input type="button" value="Add textarea with DOM" onclick="AddTextAreaDOM()" />
<input type="button" value="Add textarea w/o DOM" onclick="AddTextAreaString()" />
</body>
</html>


I would definitely recommend adding unique id's to the textarea's if you want to manipulate them later on.

The only plumbing you need is the id or reference to a control you want to place the textarea in (or document.body).
 
Back
Top