I have the following update panel with a text field limited to 9 characters only accepting numbers.
<asp:UpdatePanel ID="updatePanelsearchusers" runat="server" UpdateMode="Always">
<ContentTemplate>
<div class="formfieldarea">
<div id="searchfield1" class="searchfieldbox">
<asp:Label ID="USIDSearchlbl" runat="server" Text="USID: " CssClass="formlabel" />
<asp:TextBox ID="USIDSearchBox" runat="server" MaxLength="9" />
<cc1:FilteredTextBoxExtender ID="FilteredTextBoxExtender1" runat="server" TargetControlID="USIDSearchBox" ValidChars="0123456789" />
<asp:ImageButton ID="USIDsearchbutton" runat="server" ImageUrl="/tissuebank/images/searchButton.png" CausesValidation="true" OnClick="search1_Click" CssClass="searchbutton" />
</div>
</div>
<div>{output from search}</div>
</ContentTemplate>
</asp:UpdatePanel>
And the following JavaScript which will automatically trigger the search button if the number of characters reaches 9.
<script type="text/javascript" language="javascript">
function setupUSIDFocus() {
$('#<%=USIDSearchBox.ClientID %>').focus().keyup(function () {
if ($(this).val().length == 9) {
$('.searchbutton').first().click();
}
});
}
$(document).ready(function () { setupUSIDFocus(); });
</script>
If I have the code as above this works fine and loads with the focus being on the element USIDSearchBox as I intended, however when the update panel is updated but the event is no longer assigned to the box and the focus is lost. To fix this I added an ASP.Net Ajax control UpdatePanelAnimationExtender so that the focus and events are reassigned when the request is complete.
<AjaxControlToolkit:UpdatePanelAnimationExtender ID="upae" runat="server" TargetControlID="updatePanelsearchusers">
<Animations>
<OnUpdated>
<Sequence>
<Parallel duration="0">
<ScriptAction Script="setupUSIDFocus();" />
</Parallel>
</Sequence>
</OnUpdated>
</Animations>
</AjaxControlToolkit:UpdatePanelAnimationExtender>
And indeed this does reset the focus and the keyup event but for some reason the element does not get focus when the page is first loaded. Though the keyup event is still attached onload I am just missing the focus being on the USIDSearchBox field. If I remove the UpdatePanelAnimationExtender then I get the focus back on load, so it must be something to do with this control.
Does anyone have any idea how to get the focus onload of the page?
Alternatively, you can use 'ScriptManager.RegisterStartupScript' in 'search1_Click' to call the jQuery function after ajax update:
ScriptManager.RegisterStartupScript(this,this.GetType(),"myscript","setupUSIDFocus();",true);
Related
I have a text box and two link buttons on my web page. When I put some value on the text box, based on that value and also as soon as I leave the textbox. I want to hide or make the link button invisible.
<asp:textBox id="textBox1" runat="server">
<asp:linkButton id="link1" runat="server">
<asp:linkButton id="link2" runar="server">
when the user enter value "X" in the textbox, I want to hide Link1 and Link2 otherwise I want Link1 and Link2 to be visible.
here is my code and it is not working:
function HidePick(selectObj) {
if (selectObj.value.toUpperCase() == "D9") {
document.getElementById("LINK1").style.display = 'none';
}
}
<td><asp:TextBox ID="TXTTest1" runat="server" CssClass="cssTest" Width="30" onmouseout="javascript:HidePick(this);"
With error message:
"JavaScript runtime error: Unable to get property 'style' of undefined
or null reference
For that kind of DOM manipulation, it is easy with jQuery.
JS Fiddle - https://jsfiddle.net/p8pm6r5r
<asp:TextBox ID="textBox1" runat="server" />
<asp:LinkButton ID="link1" runat="server" Text="Button1" />
<asp:LinkButton ID="link2" runat="server" Text="Button2" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#<%= textBox1.ClientID %>").blur(function () {
if ($(this).val() === "X") {
$("#<%= link1.ClientID %>").hide();
$("#<%= link2.ClientID %>").hide();
}
});
})
</script>
In asp.net the final render id may change on page, so on javascript you need to use the .ClientID of control... you code must be as:
document.getElementById("<%=link1.ClientID%>").style.display = 'none';
Related: Accessing control client name and not ID in ASP.NET
<asp:textBox id="textBox1" runat="server">
<asp:LinkButton ID="link1" runat="server" Text="Button1" />
<asp:LinkButton ID="link2" runat="server" Text="Button2" />
Assuming you don't want to use jQuery or any library;
At the end of your htmls in .aspx page add a script tag to bind the button to mouseleave or mouseout events. Just to make sure your textbox1's id is static (the way it is in your source), once your page is rendered on the browser check for your textbox1 and see if it has still the same id if not then copy that id and replace in the below event binder line of javascript code from textbox1 to (whatever_textbox1). Same step for your link ids too.
document.getElementById("textBox1").addEventListener("mouseout",HidePick,false);
function HidePick(e){
if (e.target.value.toUpperCase() == "D9")
document.getElementById("LINK1").style.display = 'none';
}
I have an ASP button. On click of it I am opening a pop-up after doing some validations using JavaScript.
<asp:Button ID="btnHistory" runat="server" Text="History" Enabled="true" Width="100pt" OnClientClick="ShowHistoryPopup()" meta:resourcekey="btnHistory" OnInit="btnHistory_Init"/>
function ShowHistoryPopup() {
var age = $get("<%= txtSomeTextBox.ClientID %>");
var str = "";
if (Validate(age)) {
str = 'ClService.aspx?id=' + 'Null,' + age.value;
window.open(str);
}
else {
return false;
}
}
I have a radio button. Based on selected index I need to enable disable the History button. Radio button has 3 options and on 3rd option page postback happens. I need to keep the button enable on 1 st option only. I have implemented this logic with the help of Java Script and some code on OnPreRender event(for post back case).
Now the problem I am facing is, if I select option 1 or 2 and click History button, OnClientCLick event is triggering. But if I select option 3(postback) and then navigate back to option 1, onClientCLick is NOT triggering for the very first time. But on clicking the History button 2nd time its working fine. Anyone having suggestions or solution for this problem?
If I understand your problem I think what's happening is you are posting back after the History Button click which isn't what you want (as there's no click handler). Using this code works for me:
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="Radio1" />
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="Radio1" />
<asp:RadioButton ID="RadioButton3" runat="server" AutoPostBack="True" GroupName="Radio1" />
<asp:Button ID="btnHistory" runat="server" Text="History" Enabled="true" Width="100pt" OnClientClick="ShowHistoryPopup();return false;" meta:resourcekey="btnHistory" />
<script type="text/javascript">
function ShowHistoryPopup() {
alert("Here");
}
</script>
All I've added is the return false; after ShowHistoryPopup();
Also, I've used alert here for the purposes of demo, in reality we should really be using console.log('Show my message');
i want to apply a class on a asp.net label when validation fails, everything is working fine but it is requiring double-click to apply the class. First click to show the error message of the required field validator and second click applies the class. I need it in one click. Please help
<script>
function Validate()
{
//for textbox
if ($('#<% =RequiredFieldValidator1.ClientID %>').css('visibility') == 'visible')
{
$('#<% =Label1.ClientID %>').addClass('error');
}
else
{
$('#<% =Label1.ClientID %>').removeClass('error');
}
}
</script>
<asp:Label ID="Label1" runat="server" CssClass="lbl" Text="Name"></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" OnClientClick="Validate()"
Text="Submit" ValidationGroup="txt" />
You need to call your Validate() function directly on the page load.
The code is currently doing exactly what you asked it to do, when the validator is visible(after first click), and button is clicked, change color.
Add code like this to call the function onload
window.onload = Validate();
I am unable to call a Javascript function on the OnLoad event of a asp:button
HTML
<asp:Button ID="btnFromCalOpen" runat="server" Text=" > " onLoad = "AllHide()" OnClientClick ="ShowCal()" />
Javascript
function AllHide() {
alert("Hello");
}
Please Help
You will need to use JavaScript to toggle styles like you are trying
<asp:Button ID="btnFromCalOpen" runat="server" Text="" OnClientClick ="ShowCal()" style="display:none;visiblity:hidden;" />
Original Comment You can't do onLoad with JavaScript for any button. What are you hoping to accomplish? We can help figure out that solution.
You can do it at the page level. The page has a javascript onload event.
You can't do that.
Here's why. The OnLoad event in ASP.NET for a control is fired while the server is building the page (on the web server), but before it sends it to the browser (running on the user's machine).
Code on the web server can't directly call code on the browser computer (which hasn't even got the page yet).
If you just want to hide the control, just do this in your markup:
<asp:Button ID="btnFromCalOpen" runat="server" Text=" > " visible="false" OnClientClick ="ShowCal()" />
Another approach (hidden control doesn't takes up space):
<asp:Button ID="btnFromCalOpen" runat="server" Text=" > " style="display:none;" OnClientClick ="ShowCal()" />
Another approach (hidden control takes up space)
<asp:Button ID="btnFromCalOpen" runat="server" Text=" > " style="visibility:hidden;" OnClientClick ="ShowCal()" />
Old hand at ASP.NET, new to the UpdatePanel. I have a reporting page which executes a fairly length SQL query... takes about 10 seconds right now. What I would like to do is have my page fully render, with some placeholder text (Loading...) and then have the UpdatePanel kick off the actual time-consuming reporting process and render the report when it's done.
So... my theory is to use RegisterStartupScript() to kick this off and drop the string from GetPostBackEventReference() to trigger the UpdatePanel update. Some problems crop up:
1) Can I actually use GetPostBackEventReference w/ the UpdatePanel or do I need to trigger it some other way? Use this method on a button inside the Update Panel?
2) What event gets triggered when the postback reference is the UpdatePanel? It's not clear to me. I've got to call my databinding code somewhere! Again, maybe I need to use a button inside?
I had to do something very similar recently, here's how i did it (right or wrong):
The trick is a "Hidden Async Postback Trigger".
<asp:UpdatePanel ID="upFacebookImage" runat="server">
<ContentTemplate>
<!-- Your updatepanel content -->
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="hiddenAsyncTrigger" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="hiddenAsyncTrigger" runat="server" Text="AsyncUpdate" style="display:none;" />
Then from JavaScript, whenever you want to trigger the async postback, you do this:
__doPostBack('<%= hiddenAsyncTrigger.ClientID %>', 'OnClick');
In my example, i needed to trigger an async postback from a particular JS event. But you could attach it to doc ready.
I seem to remember trying #Marko Ivanovski's way, but for some reason it didn't work. I think you need to specify a "postback-able" control (ie a button) to trigger the postback.
HTH.
Updating this with my solution, I pieced together mostly from the first answer above.
I need my page to load, then then start loading content for my update panel. The panel calls some webservices and we don't want the whole page to crash in the event that the remote server doesn't respond. We don't want the wait either.
My HTML:
<asp:UpdatePanel ID="udpCheckout" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:Image ID="imgSpinner" runat="server" Visible="true" ImageUrl="~/images/ajax-loader.gif" />
<br />
<asp:Label ID="lblWait" runat="server" Visible="true" Text="Please wait..."></asp:Label>
<asp:Button ID="hiddenAsyncTrigger" runat="server" Text="AsyncUpdate" style="display:none;" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="hiddenAsyncTrigger" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
My Code behind snippets:
In page_load:
ScriptManager.RegisterStartupScript(Me.Page, Me.Page.GetType, "LoadUpdate", GetPostBackEventReference(hiddenAsyncTrigger, String.Empty), True)
And the button handler:
Sub LoadUpdatePanels(ByVal o As Object, ByVal e As EventArgs) Handles hiddenAsyncTrigger.Click
System.Threading.Thread.Sleep(5000) 'wait 5 seconds so I can see the page change
imgSpinner.Visible = False
lblWait.Text = "Content is now loaded."
'udpCheckout.Update()
End Sub
This was my test to see if I could get it working. Now to replace all of this with the real code!
Try something like this (not tested).
Set the UpdateMode of the UpdatePanel to Conditional.
Add this to your <head> section:
<script type="text/javascript">
window.onload = __doPostBack('UpdatePanel1', ''); // Replace UpdatePanel1 with the ID of your UpdatePanel
</script>
Simplifying RPM1984's very helpful earlier answer (thanks ;)) and showing some tweaks & a little more of the surrounding detail that I found necessary:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="upFacebookImage" runat="server">
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="PlaceHolderMediaPrompts" />
<asp:Button ID="hiddenAsyncTrigger" runat="server" Text="AsyncUpdate" OnClick="WasPage_Load" style="display:none;" />
</ContentTemplate>
</asp:UpdatePanel>
Note:
The hidden button's vital OnClick= parameter, this is what specifies the server function to call!
No trigger clause or triggers in the Update-panel, I am using the child controls which are automatically triggers - specifically the button Click event.
And to trigger it from client-side Javascript you can use:
document.getElementById("hiddenAsyncTrigger").click();
However, I found it necessary to prevent this being called on subsequent page loads (as it caused unnecessary page load looping & consequent flicker). See the neat little IsPostBack() check below :)
e.g. To invoke this after page load (as per the original question), I just added a call to invoke the above line of code as the onload-parameter to the main Body-tag thus:
<body onload="DoPostLoad();">
...
<script type="text/javascript">
function DoPostLoad()
{
if ( IsPostBack() != true ) // ***This is NEW and ESSENTIAL! ***
document.getElementById("hiddenAsyncTrigger").click();
}
function IsPostBack() { // Ref. https://stackoverflow.com/questions/26978112/execute-javascript-only-on-page-load-not-postback-sharepoint
var ret = '<%= Page.IsPostBack%>' == 'True';
return ret;
}
. . .
</script>
</body>