Modal PopUp - Asp.Net Ajax control toolkit - asp.net

I'm using a ModalPopUp in an Asp.net application and would like to have it closing automaticaly when user clicks "esc".
I've used the following script:
<script language="JavaScript" type="text/javascript">
function pageLoad() {
$addHandler(document, 'keydown', onKeypress);
}
function onKeypress(args) {
if (args.keyCode == Sys.UI.Key.esc) {
var mdl = $find('modalExtender').hide();
}
}
</script>
And the Modal Extender is declared like that:
<cc1:ModalPopupExtender
ID="modalExtender"
runat="server"
TargetControlID="btnPreview"
PopupControlID="PreviewPanel"
BackgroundCssClass="modalBackground"
DropShadow="true"
CancelControlID="btnFechar" />
When I press the "esc" key I'm getting this error: "Microsoft JScript runtime error: 'null' is null or not an object"
Has someone had the same problem? How was it solved?
Thank you in advance.
Josimari Martarelli

This may work for both IE and Moozilla
document.onkeyup = KeyCheck;
function KeyCheck(e)
{
//Ternary check to cover FF or IE
var KeyID = (window.event) ? event.keyCode : e.keyCode;
if (KeyID = '27') {
//Close Popup
var mdl = $find('modalExtender').hide();
}
}

Shouldn't your $find be looking for the control PreviewPanel instead of the extender? I believe your $find is returning a null because there is no HTML control with the name modalExtender.
Also, you probably need to get the ClientId for PreviewPanel instead of the ASP.NET Control name (if my guess that PreviewPanel is an ASP.NET Control is correct).

It is working now, I was missing the BehaviorID of the ModalPopUp...

Related

Control in UpdatePanel not found using $find

I have a complicated page but I created a simple ASP.NET page with the issue. I have telerik RadAsyncUpload control and a button inside an UpdatePanel as shown:
<asp:UpdatePanel ID="_updatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
...
<telerik:RadAsyncUpload ID="fileUpload" runat="server" MaxFileInputsCount="1" OnClientFilesSelected="fileUpload_ClientFilesSelected" /><br />
<asp:Button ID="_saveNewFileButton" runat="server" OnClick="_saveNewFileButton_Click"
Text="Save"/>
</ContentTemplate>
</asp:UpdatePanel>
When a file is selected I want to disable the _saveNewFileButton and change the text to "Please Wait for Attachment Upload..." but I can't seem to get hold of the button reference in javascript:
var FilesUpdateInterval = null;
//Handles client side FilesSelected event for _newFileUploadButton.
function fileUpload_ClientFilesSelected(sender, args) {
//disable the click event for submit button during upload
var submitButton = $find('<%= _saveNewFileButton.ClientID %>');
submitButton.set_text('Please Wait for Attachment Upload...')
submitButton.set_readOnly(true);
if (FilesUpdateInterval == null) {
FilesUpdateInterval = setInterval(function () { FileCheckForUploadCompletion(); }, 500);
}
}
I am getting submitButton is null error. I tried putting this javascript code outside the updatepanel and inside ContentTemplate with same result. Obviously whatever I am doing is wrong. How do I get hold of the control that is in updatepanel in javascript?
EDIT: I find out that $find works with only telerik controls. So, I have to either use document.getElementById function or JQuery with something like Steve specified. Also, I have to use RegisterClientScriptBlock. I will test with Steve suggestion and then accept the answer.
short version - use $get() or document.getElementById(), as regular HTML elements are not IScriptControls, so $find() will not give you anything, and they don't have the rich client API you are trying to use.
For example
var submitButton = $get('<%= _saveNewFileButton.ClientID %>');
submitButton.setAttribute("value", "Please Wait for Attachment Upload...");
Option 2 - use RadButton.
Using jQuery and vb with ASP.Net, I've done something similar to this, which has worked well, even if it isn't that pretty. The [Whatever] I have was a FormView that didn't always have the control. Also, I didn't use it with a button, but I think that's the syntax for changing the button text. Either way, it might give you some ideas:
$('#<%=GetButtonClientID("_saveNewFileButton")%>').attr('value', 'Please Wait for Attachment Upload...');
And then I have a function like this:
Public Function GetButtonClientID(ByVal argFieldName As String) As String
Dim tmpID As String = "0"
Dim tmpButton As Button = [Whatever].FindControl(argFieldName)
If Not tmpButton Is Nothing Then Return tmpButton.ClientID.ToString Else Return "0"
End Function

$Find returns null

I have the following JScript on a page
<script type="text/javascript">
function ProcessButtonDisable() {
var button = $find("<%=ProcessButton.ClientID %>");
button.disabled = true;
}
</script>
and later
<asp:Button ID="ProcessButton" Text="Process All" runat="server" OnClick="Process_Click" OnClientClick="ProcessButtonDisable()" />
when running the page and firing off the button i get
Microsoft JScript runtime error: Unable to set value of the property 'disabled': object is null or undefined
and the dynamic page has converted it to:
<script type="text/javascript">
function ProcessButtonDisable() {
var button = $find("ctl00_ctl00_BodyContentPlaceHolder_MainContentPlaceHolder_ProcessButton");
button.disabled = true;
}
</script>
<input type="submit" name="ctl00$ctl00$BodyContentPlaceHolder$MainContentPlaceHolder$ProcessButton" value="Process All" onclick="ProcessButtonDisable();" id="ctl00_ctl00_BodyContentPlaceHolder_MainContentPlaceHolder_ProcessButton" />
as the control is clearly defined and the client id seems to be returning the correct id i don't know whats wrong
Any help?
ps in case this is not clear from the code the purpose of this is to prevent he user from clicking on the and resending the request before the page has time to reload after the initial click
-1 to all the previous answers for assuming JQuery. $find is a function defined by the Microsoft AJAX Library. It "provides a shortcut to the findComponent method of the Sys.Application class" which gets "a reference to a Component object that has been registered with the application through the addComponent method". Try using $get() instead, which "Provides a shortcut to the getElementById method of the Sys.UI.DomElement class."
This page explores both functions in detail: The Ever-Useful $get and $find ASP.NET AJAX Shortcut Functions
$find is differ from $.find. The first one is provides a shortcut to the findComponent method of the Sys.Application class which defined by the Microsoft AJAX Library. while the second is API method from jQuery which get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
So, $find has to find Component not html DOM. and ajax Library has to be defined.
For more information:
http://msdn.microsoft.com/en-us/library/vstudio/bb397441(v=vs.100).aspx
http://api.jquery.com/find/
try this:
<script type="text/javascript">
function ProcessButtonDisable() {
var button = $("#<%=ProcessButton.ClientID %>");
button.disabled = true;
}
</script>
[edit] or
<script type="text/javascript">
function ProcessButtonDisable() {
$("#<%=ProcessButton.ClientID %>").attr("disabled", "disabled");
}
</script>
You have to select what you are "finding" in first. For example, if you select document then use the method "find" you should have the result you want.
<script type="text/javascript">
function ProcessButtonDisable() {
var button = $(document).find(("<%=ProcessButton.ClientID %>");
button.disabled = true;
}
</script>
disabled is not a jQuery object property it is a DOM element property.
Try using either:
$('selector').get(0).disabled = true
, or
$('selector').attr('disabled','disabled');
You need to use the dot notation, as find() is a jQuery function, like this:
<script type="text/javascript">
function ProcessButtonDisable() {
var button = $.find("<%=ProcessButton.ClientID %>");
button.disabled = true;
}
</script>
Also, if you are going to take the trouble to look up the DOM element in your jQuery logic, then do not bother wiring up the OnClientClick on the server control; either wire up the click event via jQuery or pass the element itself to the JavaScript function:
Using jQuery to wire up the click event (recommended):
<script type="text/javascript">
$(document).ready(function() {
$("#<%=ProcessButton.ClientID%>").click(function() {
$(this).disabled = true;
});
});
</script>
Using the OnClientClick attribute to wire up the click event and pass the element (not recommended):
<asp:Button ID="ProcessButton" Text="Process All" runat="server" OnClick="Process_Click"
OnClientClick="ProcessButtonDisable(this)" />
<script type="text/javascript">
function ProcessButtonDisable(elem) {
elem.disabled = true;
}
</script>

How to display model popup at first time page load only

I used the following code to display model popup for the first time page load,
<script type="text/javascript">
function pageload() {
var chkPostBack = '<%= Page.IsPostBack ? "true" : "false" %>';
if (chkPostBack == 'false') {
var popup = $find('ModalPopupExtender1');
if (popup != null) {
popup.show();
}
}
}
I got the following error, Please help me.
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
I would suggest to show the ModalPopup from codebehind if(!Page.IsPostBack). Therefore you can use the Show method of ModalPopupExtender.
if(!Page.IsPostBack)
{
ModalPopupExtender1.Show();
}
To enable it to be opened from serverside, you need to set the TargetControlID of the ModalPopupExtender to a hidden button:
<asp:Button ID="Hid_ShowDialog" Style="display: none" runat="server" />
I would suggest performing this code from the .net code then you can do a isPostBack check, or even if you only want it once for an entire session then once you've run the JS from the .net code, set Session("ShowPopup") to false and then check against that.
Though for this problem try changing the code block to start with:
<%# instead of <%=

ValidatorEnable is not defined

I am trying to enable and disable a required field validator using javascript but keep getting the error message ValidatorEnable is not defined. PLease find code below, any help would be great.
ASP.Net
<asp:RequiredFieldValidator EnableClientScript="True" Display="None" ID="rfvMostRecentEmployer" ControlToValidate="txtMostRecentEmployer" runat="server" ErrorMessage="Most recent employer title is a required field"></asp:RequiredFieldValidator>
Javascript
var validatorMostRecentEmployer = document.getElementById('<%= rfvMostRecentEmployer.ClientID %>');
ValidatorEnable(validatorMostRecentEmployer, !hasCv);
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
rblCV.Attributes.Add("onClick", string.Format("ShowCvOptions();"));
...
}
Make sure that function ValidatorEnable is placed before calling from any other place.
It could be that you are trying to run the JavaScript code before the asp.net validator code has been included.
If you are using jQuery then try wrapping the code in:
$(document).ready(function () {
var validatorMostRecentEmployer = document.getElementById('<% =rfvMostRecentEmployer.ClientID %>');
ValidatorEnable(validatorMostRecentEmployer, !hasCv);
});
(I also incorporated Ashwin's advice which is the correct way to reference asp.net controls from JavaScript)
ClientID could be the problem.
var validatorMostRecentEmployer = document.getElementById('<% =rfvMostRecentEmployer.ClientID %>');
ValidatorEnable(validatorMostRecentEmployer, !hasCv);
UPDATE Not an elegant solution though but it works, if nothing does.
function disableValidator()
{
var myval = document.getElememtById('<% =rfvMostRecentEmployer.ClientID %>');
myval.style.cssText="";
myval.style.display='none';
myval.style.accelerator=true;
}
After digging through the server side code I found the following code that was disabling the client side script and must have been stopping it getting registered:
//Clear client side validators
foreach (BaseValidator bv in Page.Validators)
{
bv.EnableClientScript = false;
}
Thanks to everyone who helped out with this.

TextBox causes Button Postback in ASP.NET

ASP.NET 2.0, testing in FF3 and IE7.
When I hit the 'enter' button from a text box the corresponding "OnClick" event for the first ImageButton in the page is fired. If I remove that image button, it fires the next ImageButton OnClick event on the page.
From the FireBug console, if I use JavaScript to submit the Form, this does not happen. But for whatever reason hitting enter from the textbox triggers the unrelated ImageButton event.
I found this question which had a similar problem, however the proposed answer to that solution doesn't work since ImageButtons do not have a "UseSubmitBehavior" property on them.
I don't understand why this event is firing. If I look at Request.Form, I can see that __EVENTTARGET is empty, and it is in fact posting the entire form contents (all of my textboxes), but also includes imageButton.x and imageButton.y key/value pairs.
Why is this? I suppose I could detect "enter" key presses from these text boxes with javascript, but my experience in the past is this behavior is highly variable between browsers. Any suggestions?
here's a more elegant solution
<asp:TextBox ID="TextBox1" runat="server"
onkeydown = "return (event.keyCode!=13);" >
</asp:TextBox>
read the entire post here
You could try setting a default button in an asp panel or on your form. This will let you control what happens when a user hits the enter key.
I'm having the same issue on my project.
This issue is caused because ASP.NET always will assume that the first element that inherits from IButton interface (Button and ImageButton) is the default button from the page.
Hipoteticaly, if you use an LinkButton instead of Button or ImageButton, this issue is solved.
You can find more information here on MSDN.
You can disable the Enter key from being pressed, so the user will have to click on of your ImageButtons. Just paste this javascript block onto your page:
<script type="text/javascript">
function stopRKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type=="text")) {return false;}
}
document.onkeypress = stopRKey;
</script>
Recently, I've been doing more on the client with web services and fewer postbacks. By moving my controls outside of the form element (or eliminating it altogether), the problem goes away. It's inserted by default on aspx pages, but it didn't occur to me until recently that I don't need it for much of what I do.
Its the default behaviour for an enter button press in a non text area to post back a form. You would have to handle it in a javascript method to stop the postback.
You'd just need to check the window.event.keyCode property to see if its equal to 13. If it is, reset it to 0.
function KeyPress()
{
if (window.event.keyCode == 13)
{
window.event.keyCode = 0;
}
}
I suppose I could detect "enter" key presses from these text boxes with javascript
That's what I did to get around that behaviour and it works great in IE7 and FF3. It's just a little unnatural.
Here is a generic exemple:
function TextBox1_KeyDown(sender, e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
if(key == 13 && $("#TextBox1").val() != "")
{
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("TextBox1", "", true, "", "", false, true));
}
return (key != 13);
}
I used WebForm_DoPostBackWithOptions because I needed validators to trigger. Otherwise, you might want to use __DoPostBack.
Here are the "prototypes":
function __doPostBack(eventTarget, eventArgument)
function WebForm_PostBackOptions(eventTarget, eventArgument, validation, validationGroup, actionUrl, trackFocus, clientSubmit)
{
this.eventTarget = eventTarget;
this.eventArgument = eventArgument;
this.validation = validation;
this.validationGroup = validationGroup;
this.actionUrl = actionUrl;
this.trackFocus = trackFocus;
this.clientSubmit = clientSubmit;
}
function WebForm_DoPostBackWithOptions(options)
Hope it helps.
P.S.: I used JQuery here but $get would be the same.
Here's an elegant solution I have found, in case anybody else has this problem (in case all other solution don't work for you, as they didn't work for me):
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Panel runat="server" DefaultButton="doNothingButton">
<ul id="shopping-list-ul">
</ul>
<asp:Button CssClass="invisible" runat="server" ID="doNothingButton" OnClientClick="return false;" />
</asp:Panel>
</ContentTemplate>
The textbox iself was inside the ul (generated by javascript).
Pressing enter will trigger the "doNothingButton", which will return false on client side, causing no postback at all!

Resources