$Find returns null - asp.net

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>

Related

JQuery / ASP.NET newbie questions about <asp:Button>

Hey all, having an issue getting asp buttons to interact with JQuery. I'm basically trying to hide a div that contains a form and replace it with an processing image. It works fine for me when I use an HTML input button as the trigger but when I use an aspButton nothing happens.
This works (the id of the HTML button is 'btnSubmit'):
<script>
$('#btnSubmit').click(function () {
$('#form1').fadeOut('fast', function () {
$('#processing').fadeIn('fast', function () {
});
});
});
</script>
This doesn't (the id of the ASP button is 'btnSubmitASP'):
<script>
$('#btnSubmitASP').click(function () {
$('#form1').fadeOut('fast', function () {
$('#processing').fadeIn('fast', function () {
});
});
});
</script>
Any idea what the trick is to get the asp button to do this?
Thanks
The ASP.net server ID for the control is different from the html ID. (ASP.net calls this the client ID). You can get the client id this way:
$('#<%= this.btnSubmitASP.ClientID %>').click( /* etc */ );
If you are using asp.net 4.0 you can set the button's ClientIDMode property ='Static'. This will stop the runtime from mucking with the ID.
Try this:
<script>
$('<%=btnSubmitASP.ClientID%>').click(function () {
$('#form1').fadeOut('fast', function () {
$('#processing').fadeIn('fast', function () {
});
});
});
</script>
Explanation:
ASP.NET renames all of its controls when they get sent to the client. Consequently, your ASP.NET Button does not have a client ID of "btnSubmitASP" client-side. The above code calls the server control on the server side and gets its client-id to use in the jQuery code.
Alternatively, you can use jQuery selectors:
<script>
$("[id$='_btnSubmitASP']").click(function () {
$('#form1').fadeOut('fast', function () {
$('#processing').fadeIn('fast', function () {
});
});
});
</script>
This will look for controls whose client ID ends with "_btnSubmitASP".
Another alternative to using the ClientId is to assign a unique class to the ASP:button. Your selector would then look like this:
<asp:button runat="server" CssClass="submitbutton">/<asp:button>
<script>
$("submitbutton").click(function () {
$('#form1').fadeOut('fast', function () {
$('#processing').fadeIn('fast', function () {
});
});
});
</script>
For ASP.NET buttons you should use the OnClientClick property as it has built in client side scripting added to the button to do its post back behavior. Example:
<asp:Button ID="btnSubmitASP" runat="server"
OnClientClick="yourJqueryFunction();" />
If you return false in the OnClientClick you will prevent the default behavior of the button preventing a PostBack. Doing nothing or returning true will cause the PostBack to occur. By using this method you don't need to know the name of your Button to attach the script code.
To just get your code working though, you need to get the ClientID of the control inline to creating you script so change the following line to use the ClientID property of the Button:
$('#<%= btnSubmitASP.ClientID %>').click(function () {
You need to get the ClientID because ASP.NET adds to name to namespace it and prevent duplication of names. If you look at the ASP.NET Button, the you will notice the name and ID properties have a lot more added to it like:
<input type="submit" name="ctl00$ContentPlaceHolder1$btnSubmitASP" value="Test"
id="ctl00_ContentPlaceHolder1_btnSubmitASP" />
My knowledge of jQuery is very shallow, but I can give you one tip: Remember that jQuery is being executed client-side, while the ASP button is rendered on the server and returned in the response.
Double-check the HTML markup for the button when your page is returned from the server, and make sure it's structured as you expect. Perhaps the ID attribute isn't being set as expected, for example.
Your button controller is runat="server" so this means that .NET will modify the controller's id before rendering it in HTML.
jQuery tries to use that ID to do whatever you want to do with it. But the ID is no longer the same.
Use a class instead on your button. I know it's not as fast as an ID, but it's the best way to do it because .NET will not modify your css class.
If your ASP:Button contains runat="server" then .NET will modify the ID value before it get to the DOM, so your resulting <input> will probably wind up looking like
<input id="ctl00_ContentPlaceHolder1_btnSubmitASP" />
Therefore, your jQuery selector $('#btnSubmitASP') is no longer valid because the ID has changed.
Use Firebug or Right click -> View source to confirm the actual ID value.

prevent _doPostBack getting rendered in button markup

Is it possible to prevent the _doPostBack() call getting rendered on a button?
I would like add some custom logic prior to calling the postback.
I have added an onClick event to the button
e.g.
<button id="manualSubmit" runat="server" class="manual-submit" onclick="$('#jeweller-form').hide();" />
However, this just gets rendered inline before the _doPostBack()
But the postback gets fired before the jQueryHide takes place
I would like to call my own JS function then manually trigger the postback
any ideas?
Try this:
<button runat="server" id="Test" onserverclick="Test_ServerClick">Submit</button>
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var o = $("#Test"), c = o.attr("onclick");
o
.removeAttr("onclick")
.click(function(e) {
o.fadeOut("slow", function() {
o.fadeIn("slow", function() {
c(e);
});
});
return false;
});
});
</script>
Add return false; after the client-side code in the click event. In the HTMLControl, it didn't think it rendered __doPostBack; is the control that renders the _doPostBack, and the common way to prevent that for that control is:
<asp:Button ... OnClientClick="doThis();return false;" />
Which renders these JS statements before __doPostBack.
HTH.

Modal PopUp - Asp.Net Ajax control toolkit

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...

LinkButton does not invoke on click()

Why doesn't this work?
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.myButton').click();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:LinkButton id="ttt" runat="server" PostBackUrl="~/Default.aspx" CssClass="myButton">Click</asp:LinkButton>
</div>
</form>
Do you want to submit the form, or add a Click event?
Your link button translates to
<a id="ttt" class="myButton" href="javascript:WebForm_DoPos[...]">Click</a>
, so it has no on-click javascript. Therefore, .click(); does nothing.
I haven't test it, but maybe this will work:
eval($('.myButton').attr('href'));
trigger('click') fires jQuery's click event listener which .NET isn't hooked up to. You can just fire the javascript click event which will go to (or run in this case) what is in the href attribute:
$('.myButton')[0].click();
or
($('.myButton').length ? $('.myButton') : $('<a/>'))[0].click();
If your not sure that the button is going to be present on the page.
Joe
If you need the linkbutton's OnClick server-side event to fire, you need to use __doPostback(eventTarget, eventArgument).
ex:
<asp:LinkButton ID="btnMyButton" runat="Server" OnClick="Button_Click" />
<script type="text/javascript">
function onMyClientClick(){
//do some client side stuff
//'click' the link button, form will post, Button_Click will fire on back-end
//that's two underscores
__doPostBack('<%=btnMyButton.UniqueID%>', ''); //the second parameter is required and superfluous, just use blank
}
</script>
you need to assign an event handler to fire for when the click event is raised
$(document).ready(function() {
$('.myButton', '#form1')
.click(function() {
/*
Your code to run when Click event is raised.
In this case, something like window.location = "http://..."
This can be an anonymous or named function
*/
return false; // This is required as you have set a PostbackUrl
// on the LinkButton which will post the form
// to the specified URL
});
});
I have tested the above with ASP.NET 3.5 and it works as expected.
There is also the OnClientClick attribute on the Linkbutton, which specifies client side script to run when the click event is raised.
Can I ask what you are trying to achieve?
The click event handler has to actually perform an action. Try this:
$(function () {
$('.myButton').click(function () { alert('Hello!'); });
});
you need to give the linkButton a CssClass="myButton" then use this in the top
$(document).ready(function() {
$('.myButton').click(function(){
alert("hello thar");
});
});
That's a tough one. As I understand it, you want to mimic the behavior of clicking the button in javascript code. The problem is that ASP.NET adds some fancy javascript code to the onclick handler.
When manually firing an event in jQuery, only the event code added by jQuery will be executed, not the javascript in the onclick attribute or the href attribute. So the idea is to create a new event handler that will execute the original javascript defined in attributes.
What I'm going to propose hasn't been tested, but I'll give it a shot:
$(document).ready(function() {
// redefine the event
$(".myButton").click(function() {
var href = $(this).attr("href");
if (href.substr(0,10) == "javascript:") {
new Function(href.substr(10)).call(this);
// this will make sure that "this" is
// correctly set when evaluating the javascript
// code
} else {
window.location = href;
}
return false;
});
// this will fire the click:
$(".myButton").click();
});
Just to clarify, only FireFox suffers from this issue. See http://www.devtoolshed.com/content/fix-firefox-click-event-issue. In FireFox, anchor (a) tags have no click() function to allow JavaScript code to directly simulate click events on them. They do allow you to map the click event of the anchor tag, just not to simulate it with the click() function.
Fortunately, ASP.NET puts the JavaScript postback code into the href attribute, where you can get it and run eval on it. (Or just call window.location.href = document.GetElementById('LinkButton1').href;).
Alternatively, you could just call __doPostBack('LinkButton1'); note that 'LinkButton1' should be replaced by the ClientID/UniqueID of the LinkButton to handle naming containers, e.g. UserControls, MasterPages, etc.
Jordan Rieger

Access value set using javascript in code behind in Master Page

Im executing javascript on a master page that is onClick event of a Menu item i set it to a hidden field and on Init of the Master page im not able to access this hidden field value.
Regards
State isn't available in your controls until the Load phase. Before that you have to check in Request.Form
This is the Code. In Master Page, I add the tag
<asp:HiddenField ID="hdnPath" runat="server" Value=""/>
Then I have a script tag which runs a function setScript() that is every time Master Page is loaded
<script type="text/javascript" language="javascript">
setScript();
// I Navigate through all the menu items, which is navigate
// through all the "a" tags and then all of the a tags onclick
// event i add a new function ,below is the code
<script type="text/javascript" language="javascript">
setScript();
function setScript() {
var objMenu=document.getElementById('<%=_menu.ClientID %>');
var objHyperLinks=objMenu.getElementsByTagName('a');
for(var i=0;i<objHyperLinks.length;i++) {
var pageLoc=objHyperLinks[i].href;
objHyperLinks.item(i).onclick=function (){
return setEvent(this);
};
}
}
function setEvent(Loc) {
var pageLoc=Loc+"";
var iframePath=document.location.href;
var targetPath=pageLoc;
document.getElementById('<%=hdnPath.ClientID %>').value=targetPath;
if(document.all) {
document.all.frameLoader.src=targetPath;
} else {
var frame=window.frames;
frame[0].location.href=targetPath;
}
return false;
}
I alert the value of hdnPath right after the targetPath is assigned and I get to see the assigned value.

Resources