I have a button on the form. During Page_Load event I add a new onclick attribute to the button via code behind. However when I inspect the button in firefox my attribute is not there and is being replaced with:
onclick='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("button_modal_search", "", true, "modalSearch", "", false, false))'
here is the tag before I run the app:
here's my code behind:
button_modal_search.Attributes.Add("onclick", "return showSearchSpinner()")
Anyone know how I can prevent the attribute from being overwritten?
ASP.NET indeed overrides your onclick attribute, but does provide the OnClientClick property to allow you to specify your own client-side behavior:
button_modal_search.OnClientClick = "return showSearchSpinner();"
If the value of that property is constant, you can also specify it as an attribute in the button markup itself.
There is a property OnClientClick: button_modal_search.OnClientClick="return showSearchSpinner();"
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick%28v=vs.110%29.aspx
button_modal_search.Attributes.Add("onclick", "return
showSearchSpinner()")
Above code is ok. If you do not want to postback to server, you just need to return false from javascript function.
Otherwise, it'll post back to server after running the showSearchSpinner function.
function showSearchSpinner(){
// do something
return false;
}
Note: You do not need to worry about ASP.Net replacing onclick event - onclick='javascript:WebForm_... false, false))'.
Basically showSearchSpinner javascript function intercepts ASP.Net click event, when you click on button_modal_search button.
Related
I have a button type of securebutton. I am trying to disable the button in my code behind file but the Enabled=false property is not applying to my button. Here is my code:
<cc1:SecureButton ID="sbtnPromote" runat="server" Text="Promote" IsRegExAction="True"
CssClass="button" OnClick="sbtnPromote_Click" meta:resourcekey="sbtnPromoteResource1"/>
sbtnPromote.Enabled = false;
I hope you are using a User Control for secure button.
Before, the
sbtnPromote.Enabled = false; statement, add the below statement.
Button sbtnPromote= ((Button)FindControl("sbtnPromote"));
Inside FindControl Method, Prepend your User control's Tag Name with $.
For example, if the User Control's tag Name is "Web", then you have to make the parameter "sbtnPromote" as "Web$sbtnPromote"
I like to add a validation on a label based on its visibility, in that a submit button will raise a validation message or error if the label is not visible.
I am used to the validation controls in the Toolbox, which wont allow this functionality!
It seems as though if an asp:Label's visibility is set to false, the asp.net engine will not even put it in the DOM. So you can check in javascript, using the onclick property of the (html) button to check if the label is in the DOM or not, and use asp.net's __doPostBack() javascript function to post back to the server if it is there:
<script type="text/javascript">
function testMe()
{
var lbl = document.getElementById('lblTest');
if(lbl == null)
document.getElementById('msg').innerHTML = "Error";
else
__doPostBack('testButton');
}
</script>
<asp:Label ID="lblTest" runat="server" Visible="false" Text="Hello"></asp:Label>
<button onclick="testMe();">test</button>
To be completely honest, I thought the lbl would be undefined if the label did not exist in the DOM, but Firebug revealed it is actually null. Anyway, a couple things to note is that in order for asp.net to define the __doPostBack() method, I believe you need some control in the form that has autopostback="true", and in the code-behind you can check what caused the postback in the Page_Load method like so:
if(Request.Form["__EVENTTARGET"] == "testButton") {}
I have a RadPanelBar as such...
<telerik:RadPanelBar
ID="ResourcesSubMenuRadPanelBar1"
Width="195px"
OnItemClick="RadPanelItemClick"
ExpandMode="MultipleExpandedItems"
OnClientItemClicked="RadPanelClientItemClicked"
OnClientLoad="RadPanelBarClientLoad"
runat="server"
AppendDataBoundItems="true"
EnableEmbeddedSkins="false"
OnClientItemCollapse="RadPanelClientItemClicked"
OnClientItemExpand="RadPanelClientItemClicked">
</telerik:RadPanelBar>
This all works as expected, except for one little thing. In the code behind, I explicitly set the NavigateUrl property to string.Empty but when an item is clicked, it adds a hash to the url. Obviously, this is because the href attribute has been set to "#" when the control renders the HTML.
I know that I can simply return false from the OnClientItemClicked event, but that will stop the ItemClick event from being fired on the server.
As I say, there is no real error with this code it's just bugging me (and, more importantly, the end users) that there is a # added to the URL.
Does anyone know how to stop this happening?
Try this in your OnClientItemClicking event:
eventArgs.set_cancel(true);
Ref: http://www.telerik.com/help/aspnet-ajax/panelbar-onclientitemclicking.html
And, if in case you want the post back to happen, I suppose there is a item.PostBack property (server-side). Set it to true. It should post you back - if the NavigateUrl is empty (or #).
Compatible in just about every browser, IE9 and up:
Javascript (no jQuery):
stripTelerikHashtag = function () {
[].forEach.call(
document.querySelectorAll(".rpLink"),
function (a) { a.removeAttribute("href") }
);
};
Javascript (with jQuery):
stripTelerikHashtag = function () { $(".rpLink").removeAttr("href"); };
In your ASP, set OnClientLoad on the RadPanelBar to stripTelerikHashtag.
I need to run some script by onclick() of some , checkbox particularly, to decide should i invoke WebForm_doPostBack() or not.
If I will submit form in myScript() myself, it will not cause validation of another asp.net validators, so I really need a native WebForm_doPostBack() call.
Should I handle a submit form event or are there any more "asp.net" ways to do it?
CustomValidators don't work with checkboxes:).
Just to ensure your assumptions that custom validators do not work with checkboxes is not the ONLY reason for wanting to handle the checkbox click seperately, here is some code that will validate checkboxes using ASP.NET custom validators.
Custom Validators have a ClientValidationFunction property that is called automatically when the __doPostback is called or the form is submitted.
//The Script
function validateCheckBox(source, arguments)
{
if(!source.checked) arguments.IsValid = false;//set IsValid property to false
}
//The Validator
<asp:CustomValidator ID="validateCheckbox" runat="server" ControlToValidate="CheckBox1" ErrorMessage="You REALLY need to check this!" Display="Static" ClientValidationFunction="validateCheckBox"/>
Don't you try simply putting your own validation at submit button like that :
btnSubmit.Attributes["onclick"] += "return myValidation();";
<script>
function myValidation()
{
// if you do not want to postback just return false...
return true;
}
</script>
EDIT : You can use Page_ValidationActive to programmatically enable / disable the client side validation of your page.
Page_ValidationActive A Boolean
value that indicates whether
validation should take place. Set this
variable to false to turn off
client-side validation
programmatically.
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;