In my current situation, I have a text input field and a button that, when clicked, adds additional input fields to the page.
The JavaScript code I use to achieve this functionality is as follows:
var myBtn = document.getElementById('myBtn');
var qtyOfAdds = 0;
myBtn.addEventListener('click', function (event)
{
addField();
});
var form = document.getElementById('form1');
function addField()
{
var input = document.createElement('input');
input.id = qtyOfAdds;
input.name = qtyOfAdds;
input.type = "Text";
form.insertBefore(input, myBtn);
qtyOfAdds++;
document.getElementById('AddedFieldsCount').value = qtyOfAdds;
}
On the server side, I retrieve post data to obtain all the input field data by using the following C# code:
var context = HttpContext.Current;
List<string> fieldsList = new List<string>();
string hiddenFieldData = context.Request["AddedFieldsCount"];
int addedFieldsCount = 0;
Int32.TryParse(hiddenFieldData, out addedFieldsCount);
for (int i = 0; i < addedFieldsCount; i++)
{
fieldsList.Add(context.Request[i.ToString()]);
}
This is how the HTML looks on the .aspx page:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<link href="StyleSheet.css" rel="stylesheet" />
<script src="JavaScript.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<input type="text"/>
<button type="button" id="myBtn">ADD</button>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" />
<br />
<input id="AddedFieldsCount" name="AddedFieldsCount" type="hidden" />
</form>
<script src="JavaScript.js"></script>
</body>
</html>
Can you suggest a better way to handle this scenario?