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)
Related
I am attempting to populate a html page by passing in values using QueryString and my values are passing in the QueryString but my limited to NO knowledge of JS is preventing me from being able to deduce why the textbox on the page isn't populating with the passed value.
This is my HTML showing the JS Function
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="Test.aspx.cs" Inherits="TestProject.Pages.Test" %>
<asp:Content ID="ContentHeaderID" ContentPlaceHolderID="MainContent" runat="Server">
<div class="BackgroundOfWhite">
<font class="BB">Select Instructor:</font>
<asp:DropDownList runat="server" ID="dropdown1"
AutoPostBack="true" CssClass="DropDownLists" ></asp:DropDownList>
<asp:Button runat="server" ID="btnOpenPage"
CssClass="Buttons" Text="Open Page With Params" OnClick="btnLoadPage_Click" />
<div class="White"></div>
</div>
<script type="text/javascript">
document.getElementById('InstructorName').value = Instructor;
</script>
This is my C# info here
protected void btnLoadPage_Click(object sender, EventArgs e)
{
string openthis = "http://whiskeyinthewatertestofsendingdata.html";
string Instructor = "Tyler Moore";
Response.Redirect(openthis+"?"+Instructor);
}
I feel that the issue is I am not actually calling the JS function to populate the textbox on the hmtl page, but how would I do such?
EDIT:
This is the html behind the textbox
<input id="InstructorName" name="InstructorName" maxlength="255" style="width: 240px;">
EDIT 2
I see this 1st few lines of HTML of the page...does this mean on the page load they force the fields to have a null value (which of course would mean their is no way to achieve what I am after)
<head>
<script type="text/javascript">
var forcefieldstonull =
{
"InstructorName":null,
"InstructorClass":null,
"InstructorBuilding":null,
"InstructorRoomNum":null
};
Try this:
protected void btnLoadPage_Click(object sender, EventArgs e)
{
string openthis = "http://whiskeyinthewatertestofsendingdata.html";
string Instructor = "Tyler Moore";
Response.Redirect(openthis+"?Instructor="+Instructor);
}
and then, on your page, change your javascript function to do it like this:
<script type="text/javascript">
document.getElementById('InstructorName').value = '<%=Request.QueryString["Instructor"]%>';
</script>
You have to wait for the page to be loaded completely before you can change it's elements.
Though the javascript is at the bottom it comes to my mind that it might be executed before the InstructorName div is rendered.
You should surround it with window.onload() to make sure that it is executed after the page is fully loaded. https://developer.mozilla.org/de/docs/Web/API/GlobalEventHandlers/onload
Additionally what you can do is simply check the Browsers console if the script gives you an error.
I've been trying to find the solution but it would be great if someone can take a look.
In my aspx page and C# codebehind I have the following:
aspx:
<asp:UpdatePanel runat="server" ID="UpdatePanel8" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAddTableRow" EventName="Click" />
</Triggers>
<ContentTemplate>
<div id="divDynamicFields" runat="server"></div>
</ContentTemplate>
</asp:UpdatePanel>
<div hidden>
<asp:Button ID="btnAddTableRow" runat="server" OnClick="AddTableRow" />
</div>
<script type="text/javascript">
function addTableRow(tableId) {
$('#<%=btnAddTableRow.ClientID%>').click();
}
</script>
C#:
protected void AddTableRow(object sender, EventArgs e)
{
(...)
}
The event is triggered if I don't use UpdatePanel, but when executed with UpdatePanel, there is PostBack but the C# method is not called. I've tried to understand it for some time with no avail. Any ideas? Thank you.
After a good night sleep and a fresh mind, I finally found out what is failing. The JS function addTableRow(tableId) is actually called by buttons that are dynamically created in Page_Load (the number of these buttons are not fixed, hence associating them with this JS function which clicks the hidden button that triggers the event method from codebehind). Problem is, I was generating these buttons in the following way:
Button addRowButton = new Button();
addRowButton.Text = "This is my dynamically generated button";
addRowButton.Attributes.Add("onclick", "addTableRow('" + idControl + "')");
But things started working when I've changed to:
HtmlGenericControl addRowButton = new HtmlGenericControl("input");
addRowButton.Attributes.Add("type", "button");
addRowButton.Attributes.Add("onclick", "addTableRow('" + idControl + "');");
addRowButton.Attributes.Add("value", "This is my dynamically generated button");
It's actually kind of strange, since the button created with Button() still invoked JS function addTableRows and caused PostBack but didn't invoke the code behind method. Perhaps it had to do with the page life cycle and the generated IDs for the dynamic buttons that are generated in different ways depending on creating them as Button or HtmlGenericControl, but in any ways it's working now.
I want to use some javascript code inside update panel in ASP.Net web form application using serverside code. The problem is the following code only works if i used it outside update panel but not works inside, even with alert.
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Server" OnClick="Button1_Click"/><br />
<asp:Button ID="Button2" runat="server" Text="Cleint" OnClientClick="alert('Hello World(Cleint)')"/>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
Code Behind
protected void Button1_Click(object sender, EventArgs e)
{
this.ClientScript.RegisterStartupScript(this.GetType(),
"ShowMessage", string.Format("<script type='text/javascript'>alert('{0}')</script>",
"Hello World (Server)"));
}
when running this application only the Client Click event works but not the server side event. However when removing update panel ant try again both events work.
I searched a lot and found some similar questions but all answers didn't work. I just wanna to fix problem for the example i put above. Thanks
Try to replace your code behind in the button click event with this:
ScriptManager.RegisterStartupScript(this, this.GetType(), this.ClientID, string.Format("alert('{0}')", "Server"), true);
Hope this helps.
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!
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" });