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

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.

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>

How To add TextBoxes Data in asp.net using Onblur event

I am creating a ASP.net web application where i need to add different text boxes data and save it in another text box .But using java Script and onblur event. How can we do please say in clear and understanding way because am new to It.
Thanks
You could use jQuery's blur event:
$('#TextBox1').blur(function() {
alert('Handler for .blur() called.');
});
To expand on this and do some calculation/set the value of another textbox we could do something like:
<script type="text/javascript">
$(document).ready(function () {
$("input[id$=TextBox1]").blur(function() {
$("input[id$=TextBox2]").val('Some text')
});
});
</script>

How to disable submit behaviour of asp:ImageButton?

I have a image button in a page which can be triggered on mouse click, by default it gets triggered on enter press also which i want to disable.
I know about "UseSubmitBehaviour" attribute in asp:Button, is there a way to do the same in asp:ImageButton?
I will assume you have some sort of input controls and you don't want an enter keypress to auto submit when a user accident hits the enter key. If so you can attach a javascript onkeypress event to each control that you want to disable this behavior for.
function disableEnterKey(e)
{
var key;
if (window.event) key = window.event.keyCode; // Internet Explorer
else key = e.which;
return (key != 13);
}
// In your aspx file Page_Load do the following foreach control you want to disable
// the enter key for:
txtYourTextBox.Attributes.Add("OnKeyPress", "return disableEnterKey(event);");
If you need to disable the Enter key submitting form completely. case use the OnKeyDown handler on <body> tag on your page.
The javascript code:
if (window.event.keyCode == 13)
{
event.returnValue = false;
event.cancel = true;
}
With JQuery this would be much cleaner, easier and the recommended method. You could make an extension with:
jQuery.fn.DisableEnterKey =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// return false for the enter key
return (key != 13);
})
})
};
// You can then wire it up by just adding this code for each control:
<script type="text/javascript" language="javascript">
$('#txtYourTextBox').DisableEnterKey();
</script>
If you put your content in a asp:Panel you can use the DefaultButton Property to set a different button as the default so your image button wont be clicked.
<asp:Panel runat="server" ID="pnl_Test" DefaultButton="btn_Test2">
<asp:ImageButton runat="server" ID="btn_Test1" />
<asp:Button runat="server" ID="btn_Test2" />
</asp:Panel>
In this example the btn_Test2 will be clicked when you hit enter where normally btn_Test1 would be clicked
Use Kelsey's Answer (This answer is wiki'ed)
...but please note a few things when you implement it.
I'd recommend the plain old javascript method if you're not already using jQuery. if you do that method, just return (keynum != 13) don't do something silly like if(true) return true; else return false;
You don't have to assign onkeydown from the code behind. That can be done in the markup and it's a lot cleaner when you do.
Don't disable the enter key in your entire form. You can do it in your inputs only, but if you do it in the entire form you won't be able to add a carriage return in a textarea.
If you do use jQuery, I'd recommend adding a CSS class called "disableEnterKey" and assigning it to your form elements you want to disable, then calling Kelsey's jQuery method on $(".disableEnterKey") in the document ready.
Don't answer too similar to anyone on SO, even if you don't fully agree with the answer. And even if the answer was simple and thousands of people probably have done the samething. It's "copying". Which is similar to being a "cutter" or a "tattle tale"... which is bad.
(this answer has been community wiki'ed as this question thread has gotten silly)
Use an asp:image instead. Then place some javascript code in the onclick "javascript:document.getElementById('imageClicked').setAttribute('value', 'true'); document.myform.submit();"
Set a hidden field's value (using javascript) to tell the server side code that the image was clicked.
document.getElementById('imageClicked').setAttribute('value', 'true');
Then, at the end of handling the postback on the server reset the hiddenField's value:
document.getElementById('imageClicked').setAttribute('value', 'true');
The form will execute the first button it finds on the page when you hit enter. If you can move the ImageButton further down the page so it's no longer the first button in the markup, and use CSS to position it properly, this should fix your issue. I fixed the same exact thing last week and this worked for me. I went with this solution because it didn't require JavaScript to work properly.
you want something like
<form ...>
<!-- some code here -->
<button style='display:none' onclick='return false'>here comes the magic</button>
<button>normal button </button>
</form>
See the following link.This can be solved for all default button submit problem.
http://weblog.kevinattard.com/2011/08/aspnet-disable-submit-form-on-enter-key.html
Please Use This Code
<script type="text/javascript" language="javascript">
$(document).ready(function {
$("#<%=imageClicked.ClientID%>").prop('disabled',true)
});
</script>

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

AutoPostback with TextBox loses focus

A TextBox is set to AutoPostback as changing the value should cause a number of (display-only) fields to be recalculated and displayed.
That works fine.
However, when the field is tabbed out of, the focus briefly moves on to the next field, then disappears when the page is redrawn so there is no focus anywhere.
I want the focus to be on the new field, not the textbox I've just changed.
Is there a way to work out which field had the focus and force it to have it again when the page is redrawn?
This is "by design". If you are using ASP.NET 2.0+ you can try calling the Focus method of your TextBox once the postback occurs (preferably in the TextChanged event of the TextBox).
I am not sure if there is any built-in way to track focus but I found this article in CodeProject which should do the trick.
You could also consider refresh display-only fields using AJAX UpdatePanel. This way you won't lose focus from the new field.
Also I have proposed pure server-side solution based on WebControl.Controls.TabIndex analysis, you can use it, if you like.
This is what is happening:
1) TAB on a field - client event
2) Focus on next field - client event
3) Postback - server event
4) Page redrawn - client event new page overrides preious client events
The solution of your problem is to:
a) get the element that has gained focus BEFORE postback
<script>
var idSelected;
$("input").focusin(function () {
idSelected = this.id;
});
</script>
b) store the ClientID (actually in var idSelected) somewhere (i.e. an hidden Textbox, vith ViewState = true) BEFORE postback
** b) get ClientID ** (extract from hidden TextBox and put it in var idSelected) AFTER postback
d) get the element with ClientID and set focus AFTER postback
<script>
$(document).ready(function () {
if (idSelected != null) {
$("#" + idSelected).focus();
idSelected = null;
});
});
</script>
Note: this sample scripts use JQuery.
Remember to put Jquery.js in your solution and a reference in your page
<form id="form1" runat="server" enctype="multipart/form-data" method="post">
<asp:ScriptManager runat="server" >
<Scripts>
<asp:ScriptReference Path="~/Scripts/jquery.js" ScriptMode="Auto" />
....
Note2: this solution works without AJAX.
Look at this answer: to make Javascript work over Ajax you must use code like this:
<script type="text/javascript">
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function EndRequestHandler(sender, args)
{
MyScript();
}
</script>

Resources