LinkButton does not invoke on click() - asp.net

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

Related

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

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.

How to capture 'Update' click event in ASP.NET GridView with jQuery

I need to capture the 'Update' click event with jQuery in an asp.net GridView and have no way of knowing where to start. I'm still rather new to jQuery. My GridView is attached to a SQLDataSource and, naturally, has all the bells and whistles that that combination affords. Any help would be greatly appreciated.
Simply add the script block anywhere after the GridView is declared and it should work with the default non-templated GridView column. No code in the codebehind as it is purely a Javascript solution.
Use this if you are using a Link-type GridView column:
<script type="text/javascript">
// a:contains(The text of the link here)
$('#<%= theGridViewID.ClientID %> a:contains(Update)').click(function () {
alert('Update click event captured from the link!');
// return false: stop the postback from happening
// return true or don't return anything: continue with the postback
});
</script>
Use this if you are using a Button-type GridView column and you don't want your Javascript to block the postback:
<script type="text/javascript">
// :button[value=The text of the button here]
$('#<%= theGridViewID.ClientID %> :button[value=Update]').click(function () {
alert('Update click event captured from the button!');
});
</script>
Use this if you are using a Button-type GridView column and you want to have control whether to continue with the postback or not:
<script type="text/javascript">
// :button[value=The text of the button here]
var updateButtons = $('#<%= theGridViewID.ClientID %> :button[value=Update]');
updateButtons
.attr('onclick', null)
.click(function () {
alert('Update click event captured from the button!');
var doPostBack = true; // decide whether to do postback or not
if (doPostBack) {
var index = updateButtons.index($(this));
// 'Update$' refers to the GridView command name + dollar sign
__doPostBack('<%= theGridViewID.UniqueID %>', 'Update$' + index);
}
});
</script>
Update: I think this would be a better solution in replacement of the last (3rd) script block I presented above, since you won't need to update the __doPostBack function call manually based on the command name, and as such, it should be less error-prone:
<script type="text/javascript">
// :button[value=The text of the button here]
var updateButtons = $('#<%= theGridViewID.ClientID %> :button[value=Update]');
updateButtons.each(function () {
var onclick = $(this).attr('onclick');
$(this).attr('onclick', null).click(function () {
alert('Update click event captured from the button!');
var doPostBack = true; // decide whether to do postback or not
if (doPostBack) {
onclick();
}
});
});
</script>
Credit to Aristos for this idea. :)
Ok here is my solution to capture only one update (or more) from a button.
This is the javascript code that I run on update click
<script type="text/javascript">
function NowRunTheUpdate(){
alert("ok I capture you");
}
</script>
and here is the page code
`<asp:GridView ID="MyGridView" runat="server" OnRowDataBound="MyGridView_RowDataBound" ... >`
<asp:ButtonField Text="update" CommandName="Update" ButtonType="Button" />
...
Here is the code thats run behind and set the javascript.
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// loop all data rows
foreach (DataControlFieldCell cell in e.Row.Cells)
{
// check all cells in one row
foreach (Control control in cell.Controls)
{
// I go to get the button if exist
Button button = control as Button;
if (button != null && button.CommandName == "Update")
// Add delete confirmation
button.OnClientClick = "NowRunTheUpdate();";
}
}
}
}
You need to attach a client-side event listener to the click event of the Update [link]button. I don't think it can be done using AutoGenerateEditButton="true" if you are doing it that way. You'll need to use a TemplateField so that you can manipulate the button. Then you can use jQuery to bind to the click event of the button.
Add the update column to the column templates. Convert it to a custom column, and modify it in such a way you can hook to it with jquery i.e. like adding a css class to it.
Gridview is nothing but a table with a bunch of "tr" and "td". If you understand that concept then it would be easy for you to handle anything at client side. If you have enabled auto everything then it will be a link which would result for Edit, Delete, Update or Cancel (Check View Source). The code given below should capture the update click event:
$("a:contains(Update)").live("click", function() {
//alert("hi"); do what needs to be done
return false;//would not sent the control back to server
});
HTH

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.

Disable a button on click

I have a button control. Once the user clicks on it, the click event should fire and then the button should get disabled. How can I do this? I have the option to use JQuery or JavaScript or both.
Here is my button declaration:
<asp:Button
ID="Button1"
runat="server"
Text="Click Me"
onclick="Button1_Click"
/>
On the button click code behind, I have added a Response.Write(). That should get executed and then the button should be disabled
For whatever reason, the HTML spec dictates that disabled elements should not be included in POST requests. So, if you use JavaScript to disable the HTML element in the client-side onclick event, the input element will be disabled when the browser assembles the POST request, the server won't be properly notified which element raised the postback, and it won't fire server-side click event handlers.
When you set the UseSubmitBehavior property to false, ASP.NET renders an input element of type button instead of the regular input of type submit that the ASP.NET Button control normally generates. This is important because clicking a button element does not trigger the browser's form submit event.
Instead of relying on a browser form submission, ASP.NET will render a client-side call to __doPostBack() within that button element's onclick handler. __doPostBack will raise the postback explicitly, regardless of what POST data comes through in the request.
With the postback being raised independent of the browser submit event, you're freed of the previously mentioned HTML quirk. Then, you can set an OnClientClick of "this.disabled = true;", which will render as "this.disabled = true; __doPostBack('Button1', '');", and things will work as intended.
add an OnClientClick="this.disabled = true;" to your button.
If you are using Asp.net Ajax you might want to look at using PostBack Ritalin.
Have you tried this?
Add an OnClientClick="MyFunction();" to your .NET button.
Then in the .aspx page script tags you add the following JS function:
<script type="text/javascript">
function MyFunction()
{
window.setTimeout(function ()
{
// get the button/control to disable using your favourite clientside ...
// ... control grabbing code snippet ...
// ... eg. JQUERY $('Button1'), getElementById, etc.)
document.getElementsByName('Button1').Button1.disabled = true;
// I've used "getElementsByName" because .NET will render a button with
// ... a "name" attribute, and not an "id" attribute, by default
}, 1);
}
</script>
This gives the browser a chance to post back, followed by a quick button disable.
You need to be careful that the postback occurs before you disable the button through client script. This is a common gotcha with ajax and input boxes. Disabling an input box prevents the data from being sent from the browser, even if you can see text within it while it is disabled. The answer is that you need to use jquery for this to ensure the server-side code runs first before it is disabled.
-Oisin
// to disable
this.setAttribute('disabled', true);
// to enable
this.removeAttribute('disabled');
this is a cross browser solution
There is really cool event for body tag "<"body onBeforeunload="buttonId.disabled = true;" ">"
This event triggers right before form submits, in other words your data will be submitted correctly.
When using the "this.disabled = true" method make sure you check if the page is valid before disabling the control if you have validators on the page. If validation fails you won't be able to re-enable the control without reloading the page.
if (Page_IsValid) this.disabled = true;
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function BeginRequestHandler(sender, args) {
document.getElementById('<%= lblMessage.ClientID %>').innerText = "Processing...";
document.getElementById('<%= btnSubmit.ClientID %>').innerText = "Processing";
args.get_postBackElement().disabled = true;
}
</script>
Add Script Tag in source page . change Id of button in code . You can disable the button till the process completes execution .
you can disable it server side
Button1.Enabled = false;

Resources