How to transfer data to another page and make dynamic element stay? - javascript

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

Related

How to get multiple value from html inputs that generated by C#

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();
}

Post input value into table

I'm trying to get the text from a input textfield and place the value in a table row, but each time someone posts something the oldest post moves down 1 row, here's what I have but I'm very confused now
<HTML>
<HEAD>
<SCRIPT Language="JavaScript">
<!--//
function thisPost(frm){
if (frm.postHere.value == "")
alert("Hey! You didn't enter anything!")
else
frm.postHere.value = ""
<table style="width:100%">
<tr>
<td>post + frm.postHere.value</th>
</tr>
</table>
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="thisPost">
<P>Post this: <INPUT TYPE="TEXT" NAME="postHere"><BR><BR>
<INPUT TYPE="Button" Value="Post" onClick="thisPost(this.form)">
</P>
</FORM>
</BODY>
</HTML>
Demo on Fiddle
HTML:
<label>Post this:</label>
<input type="text" name="postHere" />
<br />
<br />
<button>Post</button>
<table></table>
JavaScript:
var btn = document.getElementsByTagName("button")[0];
var inpt = document.getElementsByName("postHere")[0];
var cnt = 0;
btn.onclick = function() {
if (!inpt.value) alert("Hey! You didn't enter anything!");
else alert("The field contains the text: " + inpt.value);
var tbl = document.getElementsByTagName("table")[0];
var row = tbl.insertRow(cnt++);
var cell = row.insertCell(0);
var txt = document.createTextNode(inpt.value);
cell.appendChild(txt);
};
There's a number of syntax errors in your code, so I'm not sure how you are able to run it in its current state. Also, your markup and approach is fairly dated. I would highly recommend investing time in a cross-browser DOM framework like jQuery and then an good front-end MVW and templating framework. That aside, I've re-worked your code into a more usable form. Hopefully this will get you going.
function thisPost(){
//Use getElementById to retrieve the DOM elements you're looking for
var txtPost = document.getElementById('txtPost');
var post = txtPost.value;
if (post == "") {
alert("Hey! You didn't enter anything!")
} else {
alert("The field contains the text: " + post);
//Get a reference to your table
var table = document.getElementById('posts');
//TODO: This is unsafe and subject to script injection.
//http://en.wikipedia.org/wiki/Code_injection#HTML_Script_Injection
table.innerHTML = '<tr><td>' + post + '</td></tr>' + table.innerHTML;
txtPost.value = "";
}
}
//from: http://stackoverflow.com/a/10150042/402706
// add event cross browser
function addEvent(elem, event, fn) {
if (elem.addEventListener) {
elem.addEventListener(event, fn, false);
} else {
elem.attachEvent("on" + event, function() {
// set the this pointer same as addEventListener when fn is called
return(fn.call(elem, window.event));
});
}
}
//Don't bind events in your HTML markup, instead bind them in JavaScript.
addEvent(document.getElementById('btnPost'), 'click', thisPost);
table{
width:100%;
}
<form name="thisPost">
<p>
Post this: <input type="Text" name="postHere" id='txtPost'>
<br/><br/>
<input type="Button" value="Post" id='btnPost'/>
</p>
<table id='posts'>
</table>
</form>

Same function for different sections - relative referencing in jquery

By using relative references I am able to remove items which have been added to the list within a specfic part of the form. For example, by adding a requirement it can be deleted just from the requirement.
My issue is two fold:
Adding an item to references adds it to all three categories
When I try to add values to the other sections (qualifications) it says my input was blank.
http://jsfiddle.net/spadez/9sX6X/60/
var container = $('.copies'),
value_src = $('#current'),
maxFields = 10,
currentFields = 1;
$('.form').on('click', '.add', function () {
value_src.focus();
if ($.trim(value_src.val()) != '') {
if (currentFields < maxFields) {
var value = value_src.val();
var html = '<div class="line">' +
'<input id="accepted" type="text" value="' + value + '" />' +
'<input type="button" value="X" class="remove" />' +
'</div>';
$(html).appendTo(container);
value_src.val('');
currentFields++;
} else {
alert("You tried to add a field when there are already " + maxFields);
}
} else {
alert("You didn't enter anything");
}
})
.on('click', '.remove', function () {
value_src.focus();
$(this).parents('.line').remove();
currentFields--;
});
Is it possible to modify this code without repeating it for each section, by using relatively references such as "parent" for example. I want to use this same script for all three sections but have it so each list is independant.
I'm new to javascript so I was wondering if this is possible because I only managed to get it working on the delete.
You have to use this to get the current element. In your case this refers to the button which was clicked.
The next step is to get the input box which belongs to the button. E.g. $(this).prev(); like in this example:
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
http://jsfiddle.net/9sX6X/62/
The same is also true for your appending part. Your are appending your html to all three elements which match $('.copies'). Instead you have to try to get there from this.
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
var copies = $(this).parent().prev();
http://jsfiddle.net/9sX6X/63/
I would suggest adding a wrapping div to each section.
<div class="section">
<h4>Requirements</h4>
<div class="copies"></div>
<div class="line">
<input id="current" type="text" name="content" placeholder="Requirement" />
<input type="button" value="Add" class="add" />
</div>
</div>
Then you can do this:
var $section = $(this).closest(".section");
$(html).appendTo($section.find(".copies"));
This will add to just the related .copies element instead of to all .copies as your code does now. A similar approach can be used for all other elements as well.

javascript does not create input box

I'm really new in javascripting...(my webpage is based on jsp)
I'm trying to generate input box when option from select box is selected...
When user select any input from select box, it will send value to function init() and generate input boxes based on the value...
For example: if
<option value="IP,OS" name="sysl"><%=sysname%></option>
is selected..then it should generate something like
<tr>
<td> Enter IP:</td>
<td><input type="text" id="IP" name="IP"></td>
</tr>
<tr>
<td> Enter OS:</td>
<td><input type="text" id="OS" name="OS"></td>
</tr>
But my code does doesn't generate any...
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<title>Run Batch Script</title>
<script type="text/javascript">
function init() {
document.getElementById("bname").addEventListener("change", function(){
var value = document.getElementById("bname").value; // this gives you the selected value.
var split = value.split;
var splitsize = split.length;
for (var j=0; j<splitsize; j++){
var a = "<input type = 'text' name = '" + split[j] + "' id = '" + split[j] + "'>";
document.getElementById("inputBox").innerHTML = a;
}
// Your code to add the element that you need.
}
)};
</script>
<body>
<form action="./run?host=<%=host%>&envname=<%=envname%>" method="post" name="batchForm">
<table border="0">
<tr style="font-weight: bold; font-size: 16px;">
<td>System Name: </td>
</tr>
<tr>
<td>Select Batch : </td>
<td><select id="bname" name="bname" onclicke="init()">
<%
String src = "";
String[] temp;
String loc = root + "\\" + "Temp.txt";
int c;
int tempsize;
String param;
BufferedReader S = new BufferedReader(new FileReader(loc));
ArrayList<String> list = new ArrayList<String>();
while ((src = S.readLine()) != null){
c = 3;
param = "";
temp =src.split(":");
tempsize =temp.length;
list.add(temp[0]);
if ((tempsize >2)){
int i;
for (i=2; tempsize>i ; i++){
if((temp[i].equals("null"))){
param = "";
}
else if ((i ==2) && (temp[i] != "null")){
param = temp[i];
}
else if ((i > 2)){
param = param + "," + temp[i];
}
}
}
%>
<option value="<%=param%>" name="<%=temp[0]%>"><%=temp[0]%></option>
<%
}
BatchS.close();
%>
</select></td>
</tr>
<div id = "inputBox"></div>
What did I do wrong?
Thanks in advance!
There is some confusion about the event registration of your tag. As you said your are new to javascript, I think that it worth some explanation about event registration.
You have two ways to register some event in your HTML tag.
Using some onSomething attribute, for example:
<select onclick="myFunction()"/>
The other way, is to register the event handler using javascript:
document.getElementById("sysinfo").addEventListener("click", function(){...});
Both will work. However, in the first example the handler will be registered for you automatically when the page loads. The second way, the handler must be registered manually.
In your code you are trying to mix both.
You can either use the tag event registration, and the event is onchange (not onselect as pointed by David). OR you will have to call the init() function when the page loads. One way to do that is by putting the following code at the end of your HTML to register your event when page loads.
<script type="text/javascript">
init();
</script>
In summary I would do:
<script type="text/javascript">
function writeInputs() {
alert('writing inputs'); //helps checking if the handler is ok .. comment this when done
var value = document.getElementById("sysinfo").value; // this gives you the selected value.
var split = value.split;
var splitsize = split.length;
var code = '';
for (var j=0; j<splitsize; j++){
var a = "<input type = 'text' name = '" + split[j] + "' id = '" + split[j] + "'>";
code += a;
}
document.getElementById("inputBox").innerHTML = code;
}
</script>
<select id="sysinfo" name="sysname" onchange="writeInputs()">
The javascript is already corrected with a solution to the problem pointed by JB Nizet. I have not tested the code so there can be other problems

Add input fields to div container (javascript)

I want to add some html data to the end of a div container.
Currently, I do it with using innerHtml:
<script language="javascript">
var addid = 0;
function addInput(id){
var docstyle = document.getElementById('addlist').style.display;
if(docstyle == 'none')
document.getElementById('addlist').style.display = '';
addid++;
var text = "<div id='additem_"+addid+"'><input type='text' size='100' value='' class='buckinput' name='items[]' style='padding:5px;' /> <a href='javascript:void(0);' onclick='addInput("+addid+")' id='addlink_"+addid+"'>add more</a></div>";
document.getElementById('addlist').innerHTML += text;
}
</script>
<div id="addlist" class="alt1" style="padding:10px;">
New list items are added to the bottom of the list.
<br /><br />
</div>
The problem is that the value that was entered in the input fields is removed once another input field is added.
How can I add content without and keep the entered data?
PS: I do not use jquery.
innerHTML changes reset form elements. Instead use appendChild. See this demo http://jsfiddle.net/5sWA2/
function addInput(id) {
var addList = document.getElementById('addlist');
var docstyle = addList.style.display;
if (docstyle == 'none') addList.style.display = '';
addid++;
var text = document.createElement('div');
text.id = 'additem_' + addid;
text.innerHTML = "<input type='text' value='' class='buckinput' name='items[]' style='padding:5px;' /> <a href='javascript:void(0);' onclick='addInput(" + addid + ")' id='addlink_" + addid + "'>add more</a>";
addList.appendChild(text);
}
Take a look at this http://reference.sitepoint.com/javascript/Node/appendChild
So something like
document.getElementById('addlist').appendChild(text);

Categories