I have multiple Html inputText that is generated on page load by C#. This is my stored procedure:
ALTER PROCEDURE [dbo].[CharacteristicsFetch]
AS
BEGIN
SELECT chId, chName, chDesc
FROM Characteristics
ORDER BY chName
END
and my C# code:
public string generate_CharValues()
{
string post = "";
DataTable dt = cls.Fill_In_DataTable("CharacteristicsFetch");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
post += "<input id='" + dt.Rows[i]["chId"] + "' name='txt" + dt.Rows[i]["chId"] + "' title='" + dt.Rows[i]["chName"] + "' type='number' required='required' />";
}
}
return post;
}
I called this function from an .aspx page that I want use it:
charValues = cls.generate_CharValues();
The code will generate multiple html inputs that user must provide values for. Each input text has an Id related to it's database Id. Now I want get input values and input Ids then put them on a datatable to send it to database.
This is my try on submit test button:
DataTable dtChar = new DataTable();
dtChar.Columns.AddRange(new DataColumn[3] {
new DataColumn("chId", typeof(string)),
new DataColumn("animalId", typeof(string)),
new DataColumn("Rank", typeof(string))});
string animalId = "1";//animalId
int getcount = int.Parse(clsData.Select_One_Data("CharacteristicsGetCount", "chCount").ToString());
for(int i = 0; i < getcount; i++)
{
string chId = "";//input text id
string rank = "";//Request.Form["input text value"]
dtChar.Rows.Add(chId, animalId, rank);
}
any method with JS or JQuery will help me too. Thanks
i am sorry for the wrong answer
i was in hurry
try this
it wok for me and returns list of strings
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="check()" />
<asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button1_Click"/>
<input type="hidden" id="hdn" runat="server" />
</div>
<script>
function check() {
var val = document.getElementsByTagName("input");
var d = "";
for (var i = 0; i < val.length; i++) {
if (val[i].value != null && val[i].type == 'number') {
d += val[i].value+',';
}
}
d = d.slice(0, d.length-1);
document.getElementById("hdn").value = d;
}
</script>
</form>
and the code behind
protected void Button1_Click(object sender, EventArgs e)
{
string cd = hdn.Value;
List<string> values =cd.Split(',').ToList();
}
Related
How to make dynamic element stay after the page load and the data inside that dynamic element transfer to the next page?
I need to add a new row that contain of checkbox and textbox. I'm using Clone() method to create a new row. But then, when I click submit, the new row gone with the new data added.
Someone told me that clone() method will make a temporary element and it didn't stay after the page load. So, should I use create() new element? I also search the other method, and certain of them use asp:placeholder.
And my next problem, how I want to transfer the data inside that dynamic element? by using viewstate or session state? Because I'm not binding it into any rigid database and the form that I make, just a temporary design and the function should be work when testing being done.
For that form, I'm trying to avoid table format, and currently everything in div layout.
I've tried many method, from javascript to jquery, from clone() to create() method. But none of them give the result that I want. I'm using VS2012, in aspx web form. Your helps are really appreciated!
below is my code for row:
<div id="rows" class="block">
<div class="p2">
<input type="checkbox" class="checkbox" runat="server"/>
<input id="txt1" type="text" class="clsTxtBox10char" runat="server" maxlength="16" value="0.00" />
</div>
<div class="p3"> </div>
<div class="p4">
<input id="txt2" type="text" class="clsTxtBox10char" runat="server" maxlength="16" value="0.00"/>
</div>
<div class="p5"> </div>
<div class="p6">
<input id="txt3" type="text" class="clsTxtBox10char" runat="server" maxlength="16" value="0.00"/>
<span style="color:red;">*</span>
</div>
</div>
<div id="btn" class="block" style="text-align:center;">
<asp:Button ID="addrow" runat="server" CssClass="clsButton" Text="Add Row" />
<asp:Button ID="remove" runat="server" CssClass="clsButton" Text="Remove Row" width="90" />
<asp:Button ID="delete" runat="server" CssClass="clsButton" Text="Delete ATL"/>
</div>
below was my code for javascript:
var cloneCount = 1;
//add new row
$("#addrow").click(function () {
$('#rows')
.clone(true).find('input:text').attr('id', 'txts' + cloneCount++).val("").end()
.attr('id', 'rows' + cloneCount++, 'class', 'block')
.insertAfter('[id^=rows]:last');
return false;
});
//Remove new row
$(document).on('click', '#remove', function () {
$('#rows' + --cloneCount).remove();
return false;
});
//delete atl
$(document).on('click', '#delete', function () {
if (!$('.checkbox').prop("checked")) {
$find('.checkbox:checked').remove();
}
});
Code-behind:
protected void addrow_click(object sender, EventArgs e)
{
Panel Panel1 = new Panel();
for (int s = 0; s > 1; s++)
{
string input = string.Empty;
//div that acts like row
var row = new HtmlGenericControl("div");
row.ID = "rows" + s.ToString();
row.Attributes.Add("class", "block");
var c1 = new HtmlGenericControl("div");
c1.Attributes.Add("class", "p2");
//add inside div row
for (int i = 0; i > 0; i++)
{
input += "<input id=\"cb" + i.ToString() + "\" type=\"checkbox\" class=\"checkbox\" runat=\"server\" > </input>"
+ " " + "<input id=\"tb" + i.ToString() + "\" type=\"text\" class=\"clsTxtBox10char\" runat=\"server\"> </input>";
}
//add the string in innerHTML as
c1.InnerHtml = input;
row.Controls.Add(c1);
var c2 = new HtmlGenericControl("div");
c2.Attributes.Add("class", "p3");
row.Controls.Add(c2);
var c3 = new HtmlGenericControl("div");
c3.Attributes.Add("class", "p4");
//add inside div row
for (int i = 0; i > 0; i++)
{
input += "<input id=\"tbm" + i.ToString() + "\" type=\"text\" class=\"clsTxtBox10char\" runat=\"server\"> </input>";
}
//add the string in innerHTML as
c3.InnerHtml = input;
row.Controls.Add(c3);
var c4 = new HtmlGenericControl("div");
c4.Attributes.Add("class", "p5");
row.Controls.Add(c4);
var c5 = new HtmlGenericControl("div");
c5.Attributes.Add("class", "p6");
//add inside div row
for (int i = 0; i > 0; i++)
{
input += "<input id=\"tbe" + i.ToString() + "\" type=\"text\" class=\"clsTxtBox10char\" runat=\"server\"> </input>"
+ " " + "<span style=\"color:red;\">*</span>";
}
//add the string in innerHTML as
c5.InnerHtml = input;
row.Controls.Add(c5);
Panel1.Controls.Add(row);
Panel1.Controls.Add(new LiteralControl("<br />"));
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
Response.Redirect("new_page.aspx");
}
Try adding your dynamic rows using code behind and not jQuery.
To persist your runat="server" elements you need to have them bound to the code behind which is on the server side. I suspect this is tricky when you try to do it on the client side since there is no way the server side will know you have created a new element with jQuery.
Remove your jQuery code and allow the webpage to post back when you click on an asp:button. Then handle the click event for add, remove and delete.
To add the rows see this article: https://msdn.microsoft.com/en-us/library/kyt0fzt1.aspx
I have a simple JavaScript problem. Here is an example:
function test()
{
for(int i=1; i<5; i++)
{
var value[i] = 100*i;
var x = accountname + value[i];
document.getElementById(x).value = value + '_'+"TestName";
}
}
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<telerik:RadTextBox RenderMode="Lightweight" ID="accountname100" AutoCompleteType="HomePhone" runat="server"
Label="account #1:" /><br />
<telerik:RadTextBox RenderMode="Lightweight" ID="accountname200" AutoCompleteType="HomePhone" runat="server"
Label="account #2:" /><br />
<telerik:RadTextBox RenderMode="Lightweight" ID="accountname300" AutoCompleteType="HomePhone" runat="server"
Label="account #3:" /><br />
<telerik:RadTextBox RenderMode="Lightweight" ID="accountname400" AutoCompleteType="HomePhone" runat="server"
Label="account #4:" /><br />
</asp:Content>
I am trying to find the correct syntax so that the value of parameter "x" can be in the radtextbox correctly.
I think there are a few issues here. One is using value to set the value of the input when it has never been set and another is using accountname, when it should be a string "accountname". I have created a fiddle which is roughly what I think you're trying to achieve. Hope that helps
here is some seems to you pretended
function test() {
value = [];
for(var i=1; i<5; i++) {
value.push(100*i);
var x = accountname + value[i];
document.getElementById('accountname'+x).value = value + '_' + "TestName";
}
}
Details:
in javascript vars don't have types their type is dinamic
so to declarate any type of variable you have to do this
var number = 10;
var name = "Jhon";
var money = 3.23;
var arrayNumbers = [1,2];
I suggest you to see some basic guide to javascript.
In the below code i have a javascript function and a textbox.The validations are working perfectly.My aim if the validation fails it should clear the textbox value and cursor should be in the same textbox it should not move to other controls.
JS:
function ValidateRegExp(txtInput, REGEXP) {
var mySplitResult = new Array();
mySplitResult = REGEXP.split("~~");
var iReturn = 0;
for (i = 0; i < mySplitResult.length - 1; i++) {
var re = new RegExp(mySplitResult[i]);
if (!txtInput.match(re)) {
iReturn = iReturn + 1;
}
}
if (iReturn > 0) {
alert("Failed...");
} else {
alert("Success...");
}
}
codebehind:
txtField.Attributes.Add("onblur", "javascript:ValidateRegExp(document.getElementById('" + txtField.ClientID + "').value, '" + hidRegExp.Value + "');");
I don't know why it is not working for me this works I have just created a simple example by taking 2 textboxes
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtField" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
and this is my script
<script type="text/javascript">
function validate() {
var txt = document.getElementById("txtField");
if (txt.value === "" || txt.value.length <= 1) {
txt.value = ''; // to clear the textbox value
txt.focus(); // focus on the textbox
}
}
</script>
This is in aspx.cs file
protected void Page_Load(object sender, EventArgs e)
{
txtField.Attributes.Add("onblur", "javascript:validate()");
}
On Leave event or the blur even of every control you can call the validate() function. There is a property that focuses on invalid input. so it will stuck to the textbox till the valid data is put.
http://jqueryvalidation.org/validate/
Here is my mark up code:
<p>
<label>Reference Code:</label>
<span class="field">
<asp:TextBox ID="GenerateCode" runat="server" CssClass="smallinput random" ></asp:TextBox>
<asp:HiddenField ID="txthidden" runat="server" />
<br /><small style="color: red">Please write the code at the back of yours check</small>
</span>
</p>
here is my random function:
function randomString()
{
var chars ="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var result = '';
for (var i = 8; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}
here's how i get the random to be displayed in the textbox:
function generateRandomNumber() {
var rndStr = randomString();
$("#<%=GenerateCode.ClientID%>").val(rndStr);
$("#<%=txthidden.ClientID%>").val(rndStr);
}
window.onload = function () {
generateRandomNumber();
}
here's how i save it in the database:
string EchequeMaster = ClassEmailCheque.InsertEmailCheque(SenderID, Convert.ToInt32(ddlCurrency.SelectedIndex), Convert.ToDecimal(Amount.Text), ChequeNumber.Text, GenerateCode.Text, PendingStatus, DateTime.Now);
I solved this by using hidden field...i uodated my codes for reference.
Textboxes that are disabled (property Enabled = false) will not post back any value.
The solution is to have both a disabled textbox (to show the value to the user) and a hidden field which will post back the value. You could re write your code to something like this:
<asp:TextBox ID="txtGenerateCode" runat="server" CssClass="smallinput random" />
<asp:HiddenField ID="hdnGenerateCode" runat="server" class="random" />
function generateRandomNumber() {
var rndStr = randomString();
$(".random").val(rndStr);
}
Hope this helps!
I am binding the grid view using data table.
My task is to add new rows to my grid view dynamically when the user clicks "ADD" button in grid view it should generate new row with three text boxes.
For example: When I click the add button in the second row, a new row should be created below the second row with three text box where the user can enter details.
Can anybody help me resolve this problem? Either in jQuery/JavaScript or on the server side.
you could try this solution
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Header 1">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 3">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
inside code behind
Here’s the code block below:
private void SetInitialRow()
{
DataTable dt = new DataTable();
DataRow dr = null;
dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
dt.Columns.Add(new DataColumn("Column1", typeof(string)));
dt.Columns.Add(new DataColumn("Column2", typeof(string)));
dt.Columns.Add(new DataColumn("Column3", typeof(string)));
dr = dt.NewRow();
dr["RowNumber"] = 1;
dr["Column1"] = string.Empty;
dr["Column2"] = string.Empty;
dr["Column3"] = string.Empty;
dt.Rows.Add(dr);
//dr = dt.NewRow();
//Store the DataTable in ViewState
ViewState["CurrentTable"] = dt;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
in page load you have to call this method
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetInitialRow();
}
}
this is the method for generating the rows when clicking the Button. Here are the code blocks below:
private void AddNewRowToGrid()
{
int rowIndex =0;
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
drCurrentRow["Column1"] = box1.Text;
drCurrentRow["Column2"] = box2.Text;
drCurrentRow["Column3"] = box3.Text;
rowIndex++;
}
//add new row to DataTable
dtCurrentTable.Rows.Add(drCurrentRow);
//Store the current data to ViewState
ViewState["CurrentTable"] = dtCurrentTable;
//Rebind the Grid with the current data
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
//Set Previous Data on Postbacks
SetPreviousData();
}
this is setpreviousdata method...
private void SetPreviousData()
{
int rowIndex = 0;
if (ViewState["CurrentTable"] != null)
{
DataTable dt = (DataTable)ViewState["CurrentTable"];
if (dt.Rows.Count > 0)
{
for (int i = 1; i < dt.Rows.Count; i++)
{
TextBox box1 = (TextBox)Gridview1.Rows[rowIndex].Cells[1].FindControl("TextBox1");
TextBox box2 = (TextBox)Gridview1.Rows[rowIndex].Cells[2].FindControl("TextBox2");
TextBox box3 = (TextBox)Gridview1.Rows[rowIndex].Cells[3].FindControl("TextBox3");
box1.Text = dt.Rows[i]["Column1"].ToString();
box2.Text = dt.Rows[i]["Column2"].ToString();
box3.Text = dt.Rows[i]["Column3"].ToString();
rowIndex++;
}
}
}
}
button click event for adding new row
protected void ButtonAdd_Click(object sender, EventArgs e)
{
AddNewRowToGrid();
}
and pls take a look below image how it will generate new rows....
I hope it will helps you.....
You can use fnOpen http://www.datatables.net/ref#fnOpen. It will let you add a row directly below the row you give it. you can give that new row the html you want it to have as well.