I create html div element, but it disappears immediately in ASP.NET - javascript

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?

Every time you click that button it will cause a postback.
Fix it by stoping postback as follows:
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="clone(); return false;" />

Your button engenders a request to the server, and the ensuing response is overwriting the page with a new HTML document. Return false from the JavaScript function to prevent the asp:Button postback:
function clone() {
// your above code
return false;
}
and modify the button like
OnClientClick="return clone()"
If your asp:Button does not require interaction with the server, consider making it a <button> or <input type='button' />.

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

Related

How to persist the value of label after using getElementById() javascript function in asp.net?

This is my code --
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function myfirst() {
document.getElementById("Label1").innerHTML = "abc";
document.getElementById("Hidden1").value = document.getElementById("Label1").innerHTML;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="myfirst()" /><br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:HiddenField ID="Hidden1" runat="server" />
</div>
</form>
</body>
</html>
After running this code i get the output perfectly on the label
i.e text of label1 gets change but again it is assigned to its original "value" after page is refreshed.
Infact, i want to persist its value to "abc" after page is refreshes.
In order to maintain variables through refresh, page loads, and post back you will want to use JS session or local storage. As a page loads, it will grab the HTML that the server spits out, and other than the file caching, it will have no memory of last time the page was visited. But if you use session or local storage and load the variables from there (and set them there), then it will maintain after refresh.
Now, I'm assuming your situation is more complex than the sample you posted. If so, you will want a function that calls when the document finishes loading
Example In Jquery
$(document).ready(function() {
<insert your code to check session variable here>
});
to load the values if they exist, and when the values are modified, you will want to store them to the local storage
So using this situation as an example, you would create a session variable to say if the button has been clicked. You would check this on load. If it has been clicked, then set the text to abc, if the variable doesn't exist, or it hasn't been clicked, then do nothing
Your label just changes to "ABC" when you click Submit button. To automatically change to ABC, you should add that event to <body onload='myfirst()'> you can use ViewState or Session to store ABC when submitting form
function myfirst(){document.getElementById("Label1").innerHTML = <%: Session["NAME"].ToString()%>;}
Asp.net Label control renders to a html span element. However, only html input based controls maintain their state during postback. These are your traditional asp.net controls like TextBox, Checkbox, and, DropDownlist; in a traditional http form they translate to input with type="text", input with type="checkbox", and the select element, respectively.
However if you still want a functionality like that you'd need a composite control. This control should expose some javascript api to update the span element and an input hidden field. The control as such should assign the value in the hidden field before it renders response back to client.

Accessing asp:Textbox value inside an asp:Datalist control using Javascript

I am having major difficulty in accessing the text value of an asp:textbox control that is inside an asp:Datalist control. Here is the code:
<asp:DataList id="UserIP" DataSourceID="dsGetData" runat="server" CssClass="lblText">
<ItemTemplate>
<span class="lblText">IP Address:</span><br />
<asp:TextBox ID="tbUserIP" class="textbox_medium" runat="server" AutoPostBack="false" Text='<%# Eval("[IPAddress]") %>' /></asp:TextBox>
</ItemTemplate></asp:DataList>
I am assigning the Textbox a value from the results of a SQL query. Then I need to get that value of that Texbox using Javascript. My JavaScript code is below:
var temp = document.getElementById("<%= UserIP.FindControl("tbUserIP").ClientID %>");
I keep getting compilation error:
The name 'tbUserIP' does not exist in the current context
Any help would be appreciated tremendously.
The problem with your code is that, when you call UserIP.FindControl("tbUserIP").ClientID the tbUserIP is not available.
Notice that, to have access to such control, you will have to invoke DataBind over UserIP DataList first and only after that, maybe you will have some results that will result in rows with text boxes called tbUserIP.
To solve that, and because there are so many ways to solve it, I suggest you give a look to this:
ASP.NET Page Event Life Cycle, so you can get a clear notion of what step are you probably missing in your way to accomplish what you want.
Alternatively, and not relying so much on the ASP.NET page processing, you can work your javascript to deal with what you know that will be the end result.
Which is:
If your DataList has results, you will have something like this <input type="text" id="$somecontainerid$1$tpUserIP" value="192.168.0.1"/> in your resulting HTML right?!
So, to grab that on your javascript, assuming you can use jQuery, you can do something like this:
// grabs all the input fields with id tpUserIP (of the multiple rows).
$ipaddressFields = $("input[id*=tpUserIP]");
// alerts each one of them, if any, to show that it works.
if($ipaddressFields.length > 0){
$ipaddressFields.each(function(){
alert($(this).val());
});
}
Here's how you'd do it in JavaScript without using JQuery. I'm not sure from where you'd call the JavaScript function. So, I'm giving you two examples. I.e. one is onclick of a TextBox and the other is onclick of a button.
Here's the HTML markup
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="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 src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
function Test(obj) {
alert(obj.id); // This is the ID of the textbox clicked on
alert(obj.value); // This is the value of the textbox clicked on
}
function Test2() {
var dataListid = '<%= UserIP.ClientID %>';
var obj = document.getElementById(dataListid);
if (obj != 'undefined' || obj != null) {
for (var i = 0; i < obj.getElementsByTagName('input').length; i++) { // Loop through all TextBoxes (input elements if we talk in markup language)
alert(obj.getElementsByTagName('input')[i].value); // Here are the values of each textbox
}
}
}
</script>
<form id="form1" runat="server">
<div>
<asp:DataList id="UserIP" runat="server" CssClass="lblText" >
<ItemTemplate>
<span class="lblText">IP Address:</span><br />
<asp:TextBox ID="tbUserIP" class="textbox_medium" runat="server" AutoPostBack="false" Text='<%# String.Concat("Test", (Convert.ToInt32(Container.ItemIndex)+1))%>' onclick="Test(this);" /></asp:TextBox>
</ItemTemplate>
</asp:DataList>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Test2();" />
</div>
</form>
</body>
</html>
And here's the code behind I used. You may use your own code to bind the DataList.
using System;
using System.Collections.Generic;
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string> ips = new List<string>() {"1", "2", "3"};
UserIP.DataSource = ips;
UserIP.DataBind();
}
}
Hope this helped.
Cheers!

How to determine usercontrol selected child

I have a user control, a dropdown list, that's comprised of many component controls.
The main HtmlInputText will post back on an enter but on loss of focus it doesn't and I need that to update other controls.
I added an onblur function, and it gets called, but I only want to postback when the element getting focus isn't part of the user control.
How do I determine what is selected and if it's a child of the control?
Markup:
<%# Register Assembly="MultiDropDown" Namespace="MultiDropDownLib" TagPrefix="MultiDropDownLib" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<table style="width: 328px">
<tr>
<td>
ProductClass
</td>
<td>
<MultiDropDownLib:MultiDropDown ID="MultiDropDown1" runat="server" TextBoxClass="textboxDD"
PostOnBlur="true" />
</td>
...
And in the control:
if (PostOnBlur)
{
txtItemList.Attributes.Add("onblur", string.Format("PostBack();", this.ClientID));
}
In the PostBack I want to determine what has focus and if it's part of the control. The original control came from: http://www.codeproject.com/Articles/219977/MultiDropDown-A-multiple-selection-Dropdown-contro
This is a way to do it with javascript and jQuery:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$(":input").focus(function () {
if (this.name.indexOf("$WebUserControl1") > -1) {
alert("It is child of my control.");
}
});
});
</script>
Just replace $WebUserControl1 with the name of your user control. This could also be Dynamic if you want to. Basically all of the children of the usercontrol will contain the name of their parent because WebUserControls inherit from TemplateControl which implements the INamingContainer interface.
Good luck.

ASP.NET on button click in user control set the value of a textbox in the main page using javascript

net/C# application, I have a user control containing a button.
I am loading the control in a PlaceHolder on the main page at runtime.
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
</asp:PlaceHolder>
Code Behind:
MyControl CC = (MyControl)LoadControl("Controls/MyControl.ascx");
PlaceHolder1.Controls.Add(CC);
on the main page I have a text box and a link button. I want to do the following:
When the user clicks on the button in the user control, the textbox value is set to '5' and the link button click event is fired using javascript.
I tried the following but it did not work:
IN THE MAIN PAGE:
<asp:TextBox ID="PageBox" runat="server"></asp:TextBox>
<asp:LinkButton ID="LinkButtonPage" runat="server" onclick="LinkButtonPage_Click" Text="Submit"></asp:LinkButton>
IN THE USER CONTROL:
<script type="text/javascript">
function SetPage(a) {
var txtFld = document.getElementById("PageBox");
txtFld.value = a;
document.getElementById('LinkButtonPage').click();
return false;
}
</script>
<input type="button" id="Button1" onclick="SetPage('5');" value="Submit"/>
But when i click on the button nothig happens.
Thank you for any help
You are getting the ids of the controls wrong. You should be doing:
document.getElementById('<%=PageBox.ClientID%>');
And
document.getElementById('<%=LinkButtonPage.ClientID%>');
Also, you need to move your JavaScript function to the main page because that's the one that has the reference to both controls.
if you want to submit the page after changing the textbox value try this:
<script type="text/javascript">
function SetPage(a) {
var txtFld = document.getElementById("<%=PageBox.ClientID%>");
txtFld.value = a;
document.forms[0].submit(); // or document.forms['formname'].submit()
return false;
}
</script>
I fixed the problem by adding the function directly in the onclick event of the button
<input type="button" id="Button1" onclick="document.getElementById('PageBox').value='5';document.getElementById('LinkButtonPage').click();return false;" value="Submit"/>

Set always Focus on Textbox (ASP.NET, Updatepanel)

Hey,
Before I start to write my problem, I will excuse for my bad English and I hope you can understand me.
I have in a ASP.NET Webapplication an AJAX Updatepanel. In this Updatepanel is a
Textbox for dynamic search results. When I start to write in the Textbox, the results comes like Google suggest.
Now, the focus must be always on the Textbox (inputn field), now metter whereto the User clicks.
Currently the ASP.NET updatepanel refreshed after a few seconds when the User starts to type.
Thanks for help :-)
there is an event when updatepanel finish updated html dom
Sys.WebForms.PageRequestManager.getInstance().add_endRequest
try this
function EndRequestHandler() {
//get focus on the textbox
myTextbox.focus(); }
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
That is pretty fun but here is a possible solution. The idea is: if user gets out of the textbox (onblur), then take him back to the textbox (focusOnTxt function):
<head runat="server">
<title></title>
<script type="text/javascript">
function focusOnTxt(sender) {
sender.focus();
sender.value = sender.value;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="upnl" runat="server">
<ContentTemplate>
<asp:TextBox ID="txt" runat="server"
onblur="focusOnTxt(this)"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
And on Page_Load:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
txt.Focus();
}
}
A simple SetFocus f.e. in Page.Load should work:
ScriptManager1.SetFocus (TextBox1.ClientID)
UPDATE: according to this post following works...
Add this script into a script block in your page's head:
function SetEnd(TB){
if (TB.createTextRange){
var FieldRange = TB.createTextRange();
FieldRange.moveStart('character', TB.value.length);
FieldRange.collapse();
FieldRange.select();
}
}
Then add the onfocus event to your Textbox:
onfocus="SetEnd(this)"
In your codebehind's Page.Load or TextChanged-Event handler add the standard SetFocus call:
ScriptManager sm = ScriptManager.GetCurrent(this);
sm.SetFocus(myTextBox)

Categories