Trigger jQuery function / event from c# code-behind - javascript

I hope I will be able to explain my problem clearly.
Scenario:
Asp.net web page with UpdatePanel. Some properties of controls are changeable via UI trigger and are set in jQuery (for faster response, as this page is expected to accept input data of at least 500 records per day).
Example below, (if written in c# code, the logic is like this: txtIDNumber.Enabled = chkIsReceiptRequired.Checked; rfvIDNumber.Enabled = chkIsReceiptRequired.Checked;):
Markup:
<asp:CheckBox ID="chkReceiptRequired" runat="server" Text="Receipt required" />
<asp:TextBox runat="server" ID="txtIDNumber" Width="150px" style="float: left;" />
<asp:RequiredFieldValidator ID="rfvIDNumber" runat="server" ForeColor="Red"
ErrorMessage="Enter ID No." ControlToValidate="txtIDNumber" ValidationGroup="save" />
Snippet of default jQuery code (upon page load, chkReceiptRequired is unchecked, validator and textbox will only be enabled upon ticking chkReceiptRequired):
<script type="text/javascript">
function pageLoad(){
$('input[id$=_txtIDNumber]').prop('disabled', true);
ValidatorEnable($("[id$='rfvIDNumber']")[0], false);
$('input[id$=_chkReceiptRequired]').change(function () {
$('input[id$=_txtIDNumber]').prop('disabled', !$(this).is(':checked'));
$('input[id$=_txtIDNumber]').val(!$(this).is(':checked') ? '' : $('input[id$=_txtIDNumber]').val());
ValidatorEnable($("[id$='rfvIDNumber']")[0], $(this).is(':checked'));
});
}
</script>
I'm using this same page to load the data here to perform record update. Code snippet of data loading:
var maintableComponent = new MainTableComponent();
var maintableData = maintableComponent.GetMainTableDataById(rowId);
chkReceiptRequired.Checked = maintableData.IsReceiptRequired.Value;
txtIDNumber.Text = maintableData.IDNumber;
//todo: enable txtIDNumber and rfvIDNumber from here
The problem: by right, upon page render for update, because chkReceiptRequired is checked, supposedly txtIDNumber should be enabled. But my problem is, it is not. What can I do to enable the txtIDNumber and rfvIDNumber upon data loading from code-behind?
*I have already tried this link and this but it doesn't seem to work.
Please, please help me. The snippets I posted here are just one of many jQuery validations that I desperately need to address. Thanks in advance.

Feeling incredibly stupid right now. Figured out how to fix it after sleeping it off. :P
I just changed the default jQuery code to this:
var isReceiptRequired = $('input[id$=_chkReceiptRequired]').is(':checked');
$('input[id$=_txtIDNumber]').prop('disabled', !isReceiptRequired);
ValidatorEnable($("[id$='rfvIDNumber']")[0], isReceiptRequired);
I just remembered that the last thing in the page-cycle is rendering it on the page so the jQuery can be manipulated by the values set in the control from code-behind.

Related

Hide a Radbutton which is inside a popup when another popup form is submitted and closed upon OnClientClicking

I have a page "Main2.aspx" and inside this page, I have a button "Transactions" upon clicking this button opens a popup form "Transactions" and Inside this popup, I have coded a button "AddRadbutton" and Upon clicking this "AddRadbutton" on using Javascript URL redirection a new popup "SaveDetails" form will appear.
This "SaveDetails" form is having a "SaveRadButton", upon clicking this "SaveRadButton" my form details will be saved and the popup closes successfully.
The problem I'm facing here is, "AddRadbutton" on the "Transactions" form is still visible even after filling and submitting the details using "SaveRadButton" on "SaveDetails" form.
Earlier, I'm able to achieve the same scenario by coding on Server Side, when I have used the same "SaveDetails" popup page in User Control Page which is inside "Main1.aspx" but not here on Main2.aspx.
In Main2.aspx page I can only achieve this only when page refresh happens. but I need this "AddRadbutton" to be Hidden Immeadiately after submitting the form in "SaveDetails" popup form.
Techniques I've tried so far:
Below is the Code for AddRadButton (which is in Transactions popup)
<div id="AddDetailsDiv" runat="server" visible="true" style="width: auto; height: auto; float: left; margin-right: 10px;">
<telerik:RadButton ID="AddRadButton" runat="server" Text="Add Details"
CausesValidation="False" TabIndex="14" OnClientClicking="showDetailsWindow" UseSubmitBehavior="false" >
</telerik:RadButton>
</div>
Below is the Code for SaveRadButton (which is in SaveDetails popup)
<telerik:RadButton ID="SaveRadButton" runat="server" Text="Save" OnClick="InsertRadButton"
In Server Side for OnClick is there any chance of handling this issue using below line:
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "RadWindow", "CloseBind();", true);
I've tried coding another Javascript function and use it in OnClientClicking or OnClientClicked and call both functions but unable to achieve it because Telerik UI is not supporting or I might be missing something else.
I've tried this basic AddRadButton.Visible = false on server side, its working, but only after page refresh but I needed it to be hidden Immeadiately after popup form submission.
I've tried handling in the below code() but unable to achieve it.
function CloseBind() {
var oWindow = GetRadWindow();
oWindow.close();
oWindow.BrowserWindow.loadDetails();
}
function GetRadWindow() {
var oWindow = null;
if (window.radWindow) oWindow = window.radWindow;
else if (window.frameElement.radWindow) oWindow = window.frameElement.radWindow;
return oWindow;
}
I've searched and tried many stackoverflow-related questions, scenarios and also on many community developer sites but those didn't help me either.
Any Ideas or suggestions would be appreciated.
AddRadButton.Visible = false
should work. You will need to make sure that it's inside an if which checks for IsPostback. If that does not work for you, then it's possible that a later event in the WebForms lifecycle overrides it, maybe a render-related event is where this should be implemented, like OnPreRender. You could also register a callback script (see How can I do a call back to the code behind method using javascript (properly)?) and invoke a Javascript functions that changes the display styling to none.
I've tried to solve the problem by introducing an alert() before the window is closed so that the page refresh happens upon alert "OK" button click from the user side.
I've tried by calling an alert function in telerik: RadWindow using OnClientClose="saveDetailsWindowClose"
<telerik:RadWindowManager EnableShadow="true" Behaviors="Maximize, Close" ID="MainRadWindowManager"
DestroyOnClose="false" Opacity="100" runat="server" Modal="true" AutoSize="false"
CssClass="lte_colpopup" KeepInScreenBounds="true" RestrictionZoneID="MainContent"
VisibleStatusbar="false" style="overflow: hidden !important">
<Windows>
<telerik:RadWindow ID="MyRadWindow" ReloadOnShow="true" ShowContentDuringLoad="false" OnClientClose="saveDetailsWindowClose"
Width="950" Height="450" runat="server" Title="Person Details">
</telerik:RadWindow>
</Windows>
</telerik:RadWindowManager>
<telerik:RadScriptBlock ID="MasterScriptBlock" runat="server">
I've used below simple Javascript function to alert the User:
<script type="text/javascript">
function saveDetailsWindowClose(sender, args) {
alert('A Screen refresh is mandatory to load the details, so please click "OK" button to proceed');
window.location.reload();
}
</script>
</telerik:RadScriptBlock>
This is how I solved the Issue, fortunately, AddRadbutton on both these Main1.aspx and Main2.aspx and also on popup pages are working as intended. Luckily it didn't hamper with the closing of a window in UserControl Page on Main1.aspx which is using the same saveDetails.aspx page.

Default focus in a form or panel does not set inside a Web browser control

I am using defaultfocus property to set default focus in a form or panel. I am trying to set default focus for textbox and it works properly in a browser.
But when the same page is loaded using web-browser control in VB6 i am facing the problem. The default focus will not set when page loaded using web-browser control(VB6 Microsoft internet controls). I tried using the same for a simple form and it does not work. I tried using .focus in page load and it also not working inside web-browser control.
Then I tried refreshing the page as shown below
WebBrowser1.Navigate "url here"
WebBrowser1.Refresh
If i use refresh then focus will be set properly. But this will load the page again(it loads form of aspx again). So is there any other better solution which I can do within my ASP website? or any solution which can do the same?
I tried various methods of doing this through the WinForm code and it was not very effective. If you're needing to set the focus to a textbox, you'll probably have better luck using JavaScript.
If the textbox is a ASP.net server control, you can use:
<html>
<head>
</head>
<body>
<form runat="server">
<asp:TextBox id="FirstBox" runat="server" /><br>
<asp:TextBox id="SecondBox" runat="server" />
<script language="javascript" type="text/javascript">
var field = '<%= SecondBox.ClientID%>';
document.getElementById(field).value = field;
document.getElementById(field).focus();
document.getElementById(field).select();
</script>
</form>
</body>
</html>
This is a placeholder post.
'--- fix WebControl compatibility
lIEMajor = C_Lng(At(Split(pvGetFileVersion(CreateInstance(PROGID_FSO), GetSpecialFolder(ucsOdtSystem) & "\ieframe.dll"), "."), 0))
If lIEMajor > 7 Then
With InitRegistryAccess(ucsRegNone, "Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION")
If .ReadProperty(GetErrorProcessName(), 0, ucsRvtDword) < lIEMajor * 1000 Then
.WriteProperty GetErrorProcessName(), lIEMajor * 1000, 0, ucsRvtDword
End If
End With
End If
Code above uses lots of helper functions/classes but the idea is clear -- get IE major, if IE7 or above -> multiply major by 1000 and update HKCY_CURRENT_USER's key if needed
Will update extract snippet and include API declares later.

Unable to make ASP.NET control button fade out with JQuery

I have a simple enough problem: I have an ASP.NET control button and I want to make it fade out and then call some function (such as an alert) using JQuery. Here is what I have so far:
ASP Code for the Button:
<div id="begin">
<span id="startButtonSpan">
<asp:Button ID="startButton" class="startButton" runat="server" Text="Click Me!" OnClientClick="startButtonClick()"/>
</span>
</div>
JavaScript:
function startButtonClick()
{
$("#startButtonSpan > input").fadeOut(500, callAlert());
}
function callAlert()
{
alert("Made it here...");
}
When I click the button, the alert displays but the page does not even seem to try to perform the fadeOut. When I close the alert, the button is still there, staring at me.
Can anyone see any mistakes or does anyone have any suggestions on how I might be able to achieve the intended goal of fading out my button? Fadeout is really just my way of testing whether I can manipulate ASP controls using jQuery, so more than just the simple fadeOut, this is me trying to learn how to do that.
I tried a slightly more simple jQuery call using the code below, but it does not seem to work either:
ASP Portion:
<div id="begin">
<span id="startButtonSpan">
<asp:Button ID="startButton" class="startButton" runat="server" Text="Click Me!" OnClientClick="startButtonClick()"/>
</span>
</div>
<div id="jQueryTest" style="display:none;">
Block for testing jQuery.
<h1 id="testMessage">Child element for the ASP div.</h1>
</div>
Javascript Portion:
function startButtonClick()
{
$("#jQueryTest").css("display", "block");
$("#jQueryTest").show();
}
For this example, the text does display, but it immediately disappears again.
Any help or suggestions as to what I might be doing wrong would be greatly appreciated.
Use the class as a selector $('.startButton') instead of the ID since ASP.Net controls change their IDs dynamically when rendered by appending its Page & Control information.
$(".startButton").fadeOut(500, callAlert);
Or, if you're adamant about using the ID, here is another way to handling the selector,
$("#<%=startButton.ClientID %>")
Or, as Jacob suggested in his answer, you could ClientIDMode="Static", but this works only if your application is .Net 4.0 or above.
Also, use CssClass instead of class
<asp:Button ID="startButton" Csslass="startButton" runat="server" Text="Click Me!" />
The first example has 2 problems.
1. You should write
$("#startButton").fadeOut(500, callAlert);
and not
$("#startButton").fadeOut(500, callAlert());
2. For ASP.NET you must set ClientIDMode="Static" ortherwise asp.net will alter your id.
<asp:Button ID="startButton" ClientIDMode="Static" ... OnClientClick="startButtonClick()"/>
How about the fact that your code is fine (although other answers here should be considered) but your button is making a post back to the server and simply your browser does not have enough time to render the fade effect.
To test this, add a return false; to the OnClientClick property. This will of course cancel your action on the server but you will obtain the fade effect:
<asp: Button ... OnClientClick="startButtonClick();return false;"></asp:Button>
To work around this and still submit your request, you can try to use the ASP.NET __doPostBack method in JavaScript
ASP.NET:
<asp:Button ID="startButton" class="startButton" runat="server" Text="Click Me!" OnClientClick="startButtonClick(this);return false;"/>
JavaScript:
function startButtonClick(button)
{
$("#startButtonSpan > input").fadeOut(500, function(){__doPostBack(button.name, "")});
}
The __doPostBack method takes two arguments: the name of the control that is doing the postback and a postback argument that can be use to send more info on the server. In the case of the asp:Button, the name of the button should be sufficient to send the request without a problem.
Using this technique you will fade the button on the client and also trigger the action on the server. I cannot guarantee that this exact code will work (I don't have access to a dev environment right now) but you should get the idea.
If I could, I would like to provide another answer for those that use MasterPages and find that you can't always use $("#<%= SomeContentControl.ClientID %>") when working with Content controls.
What I do is set the MasterPage ID in my Init() like this:
protected void Page_Init( object sender, EventArgs e )
{
// this must be done in Page_Init or the controls
// will still use "ctl00_xxx", instead of "Mstr_xxx"
this.ID = "Mstr";
}
Then, you can do something like this with your jQuery:
var masterId = "Mstr",
$startButton = getContentControl("startButton"),
$message = $("#jQueryTest");
function getContentControl( ctrlId )
{
return $("#" + masterId + "_" + ctrlId);
}
function hideStartButton()
{
$startButton
.stop(true, true)
.fadeOut("slow", showMessage);
}
function showMessage()
{
$message
.stop(true, true)
.fadeIn("slow");
}
$startButton.on("click", hideStartButton);
Here is a jsFiddle that has the Mstr_ prefix already inserted as if ASP.NET rendered it.

$find() return null for defined ajax behaviour

All,
Environment: ASP.NET 2.0, AjaxToolkit build 1.0.20229.0, IE9
I am using $find() to find a behaviour of a call out extender so I can show explicitly using .show() method. Unfortunately, $find() returns null.
$find('my auto generated behvaiour Id').show();
FYI: The BehaviorID on the ValidatorCalloutExtender is generated using ClientID of the control (ClientID_ + "BehaviourID" <- is also what I use in my $find() function) because I have many instances of this control on the same page.
I looked at the rendered code and I can see JS to create that creates the behaviour:
Sys.Application.add_init(function() {
$create(AjaxControlToolkit.ValidatorCalloutBehavior ...
The $find() executes AFTER a postback in an UpdatePanel and returns always null.
EDIT (ADDED):
I created new page and below is the code, find() returns still null,- is there a bug in Ajax control tooklit for ASP.NET 2.0?
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScripManager1" runat="server" EnablePageMethods="True" >
</asp:ScriptManager>
<asp:TextBox runat="server" ID="txtInputField" />
<asp:RequiredFieldValidator runat="server" ID="valInput"
ControlToValidate="txtInputField"
ErrorMessage="ERROR STRING"
Display="none" /> <ajaxToolkit:ValidatorCalloutExtender runat="server" ID="extValInput" TargetControlID="valInput" BehaviorID="myID" />
<asp:Button runat="server" ID="btn" OnClick="btn_click" CausesValidation="True" />
<script type="text/javascript">
var obj = $find("myID");
alert(obj);
</script>
</form>
ADDED:
After observation in JS debugger, I realized that the validator callout extender only appears (is added dynamically to the DOM) when there's error, hence, if there's no error you cannot find it.
THE QUESTION NOW IS: How to reposition the call out extender baloon before displaying it? It is really catch 22, you can't access it when it is not displayed and when it is displayed, it is already to late because it displays in the wrong place.
The cause of the problem is that you try to find component before page completes component initialization. Try to access your editor in Sys.Application.add_load event handler. I tried the following code and everything works fine:
<script type="text/javascript">
Sys.Application.add_load(function() {
var obj = $find("myID");
alert(obj);
});
</script>
Edit:
To address your latest question: how you can reposition it. Callout ValidatorCalloutExtender uses PopupExtender to show it. So, you can try to bind to 'showing' and 'shown' events of the popup extender and then try to reposition callout.
<script type="text/javascript">
Sys.Application.add_load(function() {
var callouotComponent = $find("myID");
var popupBehavior = callouotComponent._popupBehavior;
popupBehavior.add_showing(function(){alert("I am showing");});
popupBehavior.add_shown(function(){alert("I was shown");});
});
</script>
Note: I didn't verify this code, but it can be used as start point.
Modified your code and verified, popup position is changing.
<script type="text/javascript">
Sys.Application.add_load(function () {
var callouotComponent = $find("myID");
//Below line is to init popup ballon, otherwise popup behaviour will return null
callouotComponent._ensureCallout();
var popupBehavior = callouotComponent._popupBehavior;
popupBehavior.set_x(100);
popupBehavior.set_y(100);
});
</script>

Creating a Button Click Event and Validating TextBoxes using Javascript

I am having so much trouble with this. I have looked everywhere so I hope someone can either explain to me how to do this or show me. Here's my problem:
I have a DataGrid filled with DataBound Items (ItemTemplate) which was created using ASP.Net.
My reason for the ItemTemplates over a regular DataBound field is to enable the Edit Mode of the DataGrid. In my ItemTemplates, I have labels to display the data and two option buttons (Edit/Delete). I've got the buttons working in the code behind (C#).
Edit places the DataGrid in Edit Mode. In the EditItemTemplates I've got DropDownLists, TextBoxes, and a Save button in place of the Edit button.
The Save button also works with the code I've written for it. All-in-all, the DataGrid works beautifully and displays everything neatly. However, there is one final job I want the Save button to do: I want it to check the TextBoxes and validate that the values entered match the criteria I have set (keep in mind that these are in EditItemTemplates).
I have Javascript already written that will check for validation. I want a modal window (that I have already set up) to display and I want the CSS of the TextBoxes in question to change.
I want to do this using Javascript but my problem is that I can't check for the Save button to create the Click event and I can't 'locate' the TextBoxes to validate them. Is there a way I can 'find' those elements while the DataGrid is in Edit Mode?
Here's a small bit of the code used to create the DataGrid if it helps:
<asp:DataGrid ID="dgCamsizer" CssClass="data" runat="server" AutoGenerateColumns="False"
GridLines="None" OnItemCommand="dgCamsizer_ItemCommand" ShowHeader="true">
<Columns>
<asp:TemplateColumn HeaderStyle-CssClass="infoHeaderDG">
<HeaderTemplate>
Operator</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="Operator" Text='<%# DataBinder.Eval(Container.DataItem, "Operator") %>'
runat="server" /></ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="EditOper" Width="40px" Text='<%# DataBinder.Eval(Container.DataItem, "Operator") %>'
runat="server"></asp:TextBox></EditItemTemplate>
<HeaderStyle CssClass="infoHeaderDG"></HeaderStyle>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderStyle-CssClass="infoHeaderDG">
<ItemTemplate>
<asp:Button ID="Edit" Text="Edit" CommandName="Edit" runat="server" /></ItemTemplate>
<EditItemTemplate>
<asp:Button ID="Save" Text="Save" CommandName="Save" runat="server" /></EditItemTemplate>
<HeaderStyle CssClass="infoHeaderDG"></HeaderStyle>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>
Perhaps I should re-phase my question: I managed to 'find' the TextBoxes thanks to Zetlen. I've also managed to get the values. Now... How do I use those values to test for validation?
Here is the code I used to get the values:
$("#<%=dgCamsizer.ClientID %> :text").each(function () {
alert($(this).val());
});
ASP.NET webforms are hard to work with in JavaScript, because the IDs of your HTML elements change during the page lifecycle! The input you're calling "EditOper" will get an HTML ID of something like "dgCamSizer_ctl102_EditOper". One thing you can do is collect these elements on pageload in a cache of DOM element references. I recommend using jQuery or a similar DOM querying library.
<script type="text/javascript">
$(document).ready(function() {
var $editorElms = {},
idSeparator = "_"; // the underscore is ASP.NET's default ID separator, but this can be changed if you wish with the IDSeparator property.
$('#dgCamSizer input').each(function() {
$editorElms[this.id.split('_').pop()] = $(this);
});
// now you can access every input using the $editorElms hash.
// e.g.
function someValidationRoutine() {
if (!$editorElms.EditOper.val()) {
someErrorDisplayer("EditOper must not be blank.");
return false;
}
}
})
</script>
And, again using jQuery, the Save button shouldn't be too tough to find.
var $saveButton = $('#dgCamSizer :submit[value=Save]');
So you can bind the event that way:
$saveButton.click(function(e) {
if (!someValidationRoutine()) {
e.preventDefault();
}
});
This is not the most high-performance solution--selectors of that complexity are always a bit slower. But it gets the job done without messing too much with the DataGrid.
So I managed to solve my own problems and answer my own question. I was able to get the id's of all of the TextBoxes and I even placed them into an array to be used for my validations. Here's what I used to do all of this:
var i = 0;
var data = [];
$("#<%=dgCamsizer.ClientID %> :text").each(function () {
data[i] = $(this).attr("id");
i++;
});

Categories