This is frustrating, I want to simply create new input field
inside div
on my aspx
page when button
is clicked. I use javascript function witch appends new child element(input field) to existing div
. It all looks like this:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="Pages_test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function clone() {
var html = document.createElement("input");
html.setAttribute("id", 1);
html.setAttribute("name", "dejan");
html.setAttribute("value", "some text");
html.setAttribute("type", "text");
document.getElementById("panj").appendChild(html);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="panj">
Djubrov
</div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="clone()" />
</form>
</body>
</html>
Funny thing is that text element with set text value flashes for second when i click the button but it disappears afterwords. Do I missing something?
If you need the value from this generated text field in code behind, you would be much better off not to create it dynamically via Javascript. You could just create a normal textbox and set it to be initially invisible like so:
<asp:TextBox ID="yourTextboxID" Visible="False" runat="server" />
When the button is pressed, handle the event in the code behind and make the textbox visible:
yourTextboxID.Visible = True;
Viewstate will keep the values across postbacks.
If each button press should create an additional textbox, you could also do this in the codebehind, i.e. use a placeholder in the ascx and then attach a new textbox to it with each button press:
yourPlaceholderID.Controls.Add(new TextBox() { ID = "textbox1" });