Call javascript function from asp Textbox - javascript

I have seen some post regarding this question but i cannot find a solution for my problem. I have a text box and through autocompleteextender i am searching records from database. which works fine.
<ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" CombineScripts="false">
</ajaxToolkit:ToolkitScriptManager>
<asp:TextBox ID="txtAccNo" runat="server" Width="125px" ToolTip="Account Number">
</asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender2" runat="server"
TargetControlID="txtAccNo" MinimumPrefixLength="2" EnableCaching="true" CompletionSetCount="10"
CompletionInterval="1000" CompletionListCssClass="autoExtender" CompletionListItemCssClass="autoExtenderList"
ServiceMethod="getAccountNumbers" ServicePath="WebServiceGetAccounts.asmx">
</asp:AutoCompleteExtender>
Now i want to show some loading gif(http://loadinggif.com/images/image-selection/3.gif) in textbox when webservice searches for data. For that i want javascript function to load this gif in textbox. and when webservice shows some data i want to remove this gif. In addition i want to load this gif if user puts atleast 2 numbers in textbox. as MinimumPrefixLength property of autocompleteextender is set to 2. if Anyone can help? i will be very thankful.

Hope below solution/logic help you out.
<asp:TextBox ID="txtAccNo" runat="server" Width="125px" onchange="return inputText_Changed();" ToolTip="Account Number"> </asp:TextBox>
<script type="text/javascript">
function inputText_Changed() {
var accountNo = document.getElementById('<%= txtAccNo.ClientID %>').value.trim();
//check minimum input characters MinimumPrefixLength
if (accountNo.length >= 2) {
// remove / hide your gif image
return true;
}
else {
// Add / show your gif image
return false;
}
}
</script> `
Let me know if any query you have
Thanks
Happy Coding

there are some properties of AutoCompleteExtender like OnClientPopulating and OnClientCompleted... use those properties to perform any task. in my case i wanted to load a gif. i created a css class and a javascript function to load gif while using properties of AutoCompleteExtender.
onclienthiding="OnClientCompleted" onclientpopulated="OnClientCompleted"
JavaScript Function:
function OnClientPopulating(sender, e) {
sender._element.className = "loading";
}
function OnClientCompleted(sender, e) {
sender._element.className = "";
}
CSS Class:
.loading
{
background-image: url(img/loading.gif);
background-position: right;
background-repeat: no-repeat;
}

Related

How to change the value of an asp label with JavaScript?

I'm trying to add an error label to the top of a panel I have. I have a button created in C# on page load that calls a JavaScript function that I want to display an error message on my panel when clicked.
C#:
private void CreateButton(int pID, string changeType)
{
ASPxButton btn = new ASPxButton();
btn.Text = "Execute Request";
btn.ID = "btn" + changeType;
btn.AutoPostBack = false;
btn.ClientSideEvents.Click = GetClientSideEventHandler(string.Format("OnProcessRequest(s, e, '{0}','{1}')", pID.ToString(), changeType));
TableRow oRow = new TableRow();
TableCell oCell = new TableCell();
oCell.CssClass = "table-cell";
oCell.Controls.Add(btn);
oRow.Cells.Add(oCell);
tblButtons.Rows.Add(oRow);
}
JS:
function OnProcessRequest$(pID, pChangeType) {
document.getElementById('errLabel').value = "Test";
}
ASPX:
<asp:Label ID="errLabel" runat="server"/>
When this code runs, it always throws the following error:
Error: Unable to set property 'value' of undefined or null reference.
I have tried also using:
document.getElementById('<%=errLabel.ClientID%>').value = "Test";
but this also throws the error.
How can I change the value of this label when this button is clicked in JS?
Ok, to change a asp.net label in JavaScript, you can do this:
(we assume you set the label client id mode>
So, if we have label on the page, you can do this:
<asp:Label ID="Label1" runat="server" Text="" ClientIDMode="Static"></asp:Label>
JavaScript to change above is this:
var lbl = document.getElementById('<%=Label1.ClientID%>');
lbl.innerText = "Js lable text changed";
Or
lbl.innerHTML = "<h2>this is some big text by js</h2>"
Be VERY careful with case, and VERY careful with extra spaces etc. in the get Element.
Also, do NOT forget to include the Text="" in your label!!!! (you are missing this!!!).
JavaScript is VERY flakey - one small wrong move, and it just rolls over and goes home. (and the debugger in browsers is on par with a trip to the dentist).
You can also use jQuery.
The above thus becomes this:
var lbl = $('#Label1');
lbl1.text("js jquery text change");
Now, lets do the same for a text box.
our asp.net text box:
<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static" ></asp:TextBox>
JavaScript:
var txt = document.getElementById('<%=TextBox1.ClientID%>');
txt.value = "This is js text for text box";
And as jQuery:
var txt = $('#TextBox1');
txt.val("js jquery text for the text box");
So, for a asp.net label? You use innerText, or innerHTML.
(or text("your text here") with jQuery)
and with jQuery, you use .value without ()
Try adding ClientIDMode="Static" to your label if that property is available to you. Or you could add ClientID="errLabel" as an alternative. What's happening is asp.net will automatically give your field a generated id for closure on the client side so it will not match your id "errLabel".
<asp:Label runat="server" ID="errLabel" ClientIDMode="Static"></asp:Label>
OR
<asp:Label runat="server" ID="errLabel" ClientID="errLabel"></asp:Label>
https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.control.clientidmode?view=netframework-4.8#System_Web_UI_Control_ClientIDMode

Asp.Net Control Value return undefined in Jquery

In my project i need change visible of dynamic asp control when click label based on textbox values. So i first tried to get textbox value when click label but its return undefined. I am search and get two methods i tried that also it return same.
My Try :
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$(document).on("click", "#lblShow", function() {
alert($('#<%=txtTotalVersion.ClientID%>').val());
alert($('input[id$=txtTotalVersion]').val());
var xTotlal =$('#<%=txtTotalVersion.ClientID%>').val()
var i = 0;
for (i = 0; i < xTotlal; i++) {
$('#createDiv' + i).style.display = "blcok";
$('#createDiv1' + i).style.display = "block";
$('#createDiv2' + i).style.display = "block";
$('#createDiv3' + i).style.display = "block";
}
});
});
</script>
HTML
<div id="DivCompName">
<asp:TextBox runat=server ID="txtTotalVersion" Visible="false"></asp:TextBox>
<asp:TextBox runat=server ID="txtCurrentDisplay" Visible="false"></asp:TextBox>
</div>
First two alert return undefined.
Visible="false" is asp.net attribute, in this case your control will not be rendered at the client side. So your client script won't find the control as it doesn't exists!
If you want to store some value at client side and don't want to display it then you can use HiddenFields or you can make the same control hidden by using css style display:none;. (Don't use Visible="false" for this)
you can add ClientIDMode=Static and call it from your jquery
<asp:TextBox runat=server ID="txtTotalVersion" Visible="false" ClientIDMode="Static"></asp:TextBox>
<script>
$(document).ready(function () {
alert("#txtTotalVersion").val();
})
</script>
reason is, the client id for your control might not be as it is assigned with ID="xxx", if the control is inside of another asp.net server control, after adding the ClientIDMode, you are telling your server to treat this control with a static ID
to learn more: msdn

Add processing image to text in UpdatePanel control

I have an UpdatePanel that displays the text, 'Please wait while the files are created...', when the user clicks the button 'Create Files'. Once the processing is completed, the text is updated to display 'Processing completed'. This works correctly.
What I want to do is add a processing image to the left of the text to show the user that the application is working. I have added the image. When I set the 'Visible' attribute to true, it displays as a spinning circle. What I want to do is display the image only when the text, 'Please wait while the files are created...'.
So initially, I set the image to, Visible-"false". I thought I could just add a line of code to the javascript that displays the text, 'Please wait..' but it is not displaying. Below is my code:
JavaScript:
script type="text/javascript">
$(document).ready(function () {
bindButton();
});
function bindButton() {
$('#<%=btnCreateFiles.ClientID%>').on('click', function () {
$('#<%=lblCaption.ClientID%>').html('Please wait while the label files are being created...');
//I thought I could just add this line and the image would at least display.
//But it does not display. I have also tried setting it to 'visible' and that
//doesn't work either.
// document.getElementById("<%=imgProcessing.ClientID%>").style.display='inline-block';
});
}
</script>
HTML:
<asp:UpdatePanel ID="ProgressUpdatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Image ID="imgProcessing" runat="server" CssClass="floatleft" ImageUrl="~/Images/updateProgress.gif" Visible="false" />
<asp:Label ID="lblCaption" runat="server" CssClass="label" ForeColor="Red" Visible="true"></asp:Label>
<asp:Button ID="btnCreateFiles" runat="server" Text="Create Labels Files" Width="206px" CssClass="label" Height="37px" OnClick="btnCreateFiles_Click" style="float: right"/>
</ContentTemplate>
</asp:UpdatePanel>
This is the Code Behind that is in the Click event:
protected void btnCreateFiles_Click(object sender, EventArgs e)
{
string tstrIssueMonth = string.Empty;
string tstrFolderPath = string.Empty;
try
{
ScriptManager.RegisterClientScriptBlock(Page, typeof(string), "bindButton", "bindButton();", true);
//do processing here
ProgressUpdatePanel.ContentTemplateContainer.Controls.Add(lblCaption);
ProgressUpdatePanel.Update();
lblCaption.ForeColor = Color.Green;
lblCaption.Text = "Processing completed...files have been created.";
}
}
So, I need to be able to show the processing image when the text, 'Please wait...' is shown and when the text 'Processing completed...' is shown the image is not visible.
How do I do that?
Thanks,

How to close a RadWindow not usting the default "X"?

I have a RadWindow as following:
<telerik:RadWindow ID="PIQRadWindow" Modal="true" runat="server" Skin="Default" Behaviors="Close,Move" CssClass="RadWindowCustomClass" VisibleStatusbar="false" width="400px" OnClientClose="RadWindowClose">
<ContentTemplate>
<pd:uc_PopupDropdown ID="pdPIQScore" enableviewstate="False" Draggable="true" isInternal="true" ISOC="ProjectInstructionQuality" DivContent = "pdPIQScore" ScriptPrefix = "OFS_" runat="server" />
</ContentTemplate>
</telerik:RadWindow>
I want it to be closed within a onclick event I defined. I tried to use
function getRadWindow() {
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow;
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
return oWindow;
}
function clientClose() {
getRadWindow().close();
}
But it's not working for me. Error message: "window.frameElement is null".
Anyone has ideas?
You must use $find() when using the ContentTemplate. You can either keep a reference in a global JS variable (you can populate the variable in Sys.Application.Load), or create functions that will open and close the dialog and call them whenever needed. Check this demo's code: http://demos.telerik.com/aspnet-ajax/window/examples/contenttemplatevsnavigateurl/defaultcs.aspx.
Have you checked out this post? If so, please share some more of your code so we can see exactly whats going on.
How to close the radwindow on serverside and refresh the parent page

Show/Hide Database Field based on Null/Not Null ASP.NET

I am trying to hide a data field if it is null via ASP.NET.
I have the following setup:
<script runat="server" type="text/vb">
// target the id called test
var test = document.getElementById("test");
// if test is not empty, show
// else hide test
if (test.value != null){
document.getElementById("test").style.visibility = visible;
}else{
document.getElementById("test").style.visibility = hidden;
}
<p><asp:Label runat="server" id="test"><%# Eval("DBField")%></asp:Label></p>
Am I way off here? I am getting error in whatever I try. I don't think it should be so complicated however...any thoughts/recommendations would be greatly appreciated.
Thank you in advanced,
Without knowing what your error is it's hard to give you an answer. One thing that jumps out is that you are not using the ClientId of the asp.net control. Try changing this:
var test = document.getElementById("test");
to this:
var test = document.getElementById("<%=test.ClientID%>");
When you assign an ID to an asp.net control, that is not the ID that gets rendered. Give this article a read for more info on that.
There are a few possible issues here:
Since you are using a server control, depending on what its parent is, the ASP.NET runtime could be changing its ID. If you View Source on your page it may show an ID like "ctl00_main_test" or something similar. To get aroud this you have to do the followinh:
var test = document.getElementById("<%= test.ClientID %>");
if (test.text != null){
test.style.visibility = 'visible';
}else{
test.style..visibility = 'hidden';
}
Since "visibility" maps to a CSS style, you probably have to use quotes around "visible" and "hidden"
Lastly, getElementByID should work well for all modern browsers, but older browsers could have flaky implementations. I suggest looking at jquery to simplify this code:
if ( $('#<%=test.ClientID>').text() != '' && $('#<%=test.ClientID%>').text() != null){
$('#<%=test.ClientID%>').show();
}else{
$('#<%=test.ClientID%>').hide();
}
You need to test against empty string in JavaScript, like this:
var test = document.getElementById("<%=test.ClientID%>");
if (test){
test.style.visibility = (test.value == "" ? "hidden" : "visible");
}
EDIT
I just noticed that you're using databinding syntax, which makes me think that this Label is inside of a grid or something. You can try something like this instead:
<asp:Label ID="test" runat="server" Visible='<%#(String.IsNullOrEmpty(Eval("DBField")) == false)%>'><%#Eval("DBField")</asp:Label>
I was able to hide data via the following code:
<asp:PlaceHolder ID="PlaceHolder" runat="server" Visible='<%# IIf((Eval("test")).ToString().Length > 0, "true", "false") %>'>
<h3>test</h3>
<asp:Label ID="test" runat="server" Text='<%# Bind("test") %>'></asp:Label>
</asp:PlaceHolder>
Span tags do not have a value:
if ($('#<%=test.ClientID%>').html() != "") //jQuery
or
if (document.getElementById("<%=test.ClientID%>").innerText != "")

Categories