Related
My UserControl has a TextBox, that is subscribed to OnTextChanged event. However, since a lots of business logic and integrations happens on server, I want to disable a form while postback is being performed with some client-side javascript and I'm not sure how to achieve it the right way.
Can I solve this with ClientScriptManager.GetPostBackEventReference?
Edit: as my question seems to be misunderstood:
TextBox is subscribed to event OnTextChanged="tb_TextChanged" which will result on client in onchange=__doPostBack('tb') so I want to inject my javascript disableForm() to onchange DOM event. I know how to implement disableForm(), the question is how to inject my javascript properly?
I would suggest you use the javascript onblur event and check if the field value is changed. If so, you can use jQuery like the below to disable the form elements.
To disable a form element such as a text input or a button (with a made-up id: #elm):
$("#elm").attr("disabled", "disabled");
To enable a disabled form element:
$("#elm").removeAttr("disabled");
You should be able to do this with some simple JavaScript:
<script type="text/javascript">
disableFormFields = function(){
if (document.all || document.getElementById){
for (i = 0; i < document.forms[0].elements.length; i++){
var el = document.forms[0].elements[i];
if (el){
el.disabled = true;
}
}
}
}
</script>
<asp:TextBox ID="TextBox1" runat="server" onchange="disableFormFields();" OnTextChanged="TextBox1_TextChanged" />
html code:
<asp:Button runat="server" ID="btnTest" Text="Test" OnClick="btnTest_Click" />
Jquery Code:
$('[id$=btnTest]').click(function(){
$('[id$=btnTest]').attr('disabled', 'true');
});
CodeBehind:
protected void btnTest_Click(object sender, EventArgs e)
{
//here not come.
}
Code Behind btnTest event not work ?
I think that making the button disabled in the click event handler is preventing the postback. Try executing the disabling code after some time:
$('[id$=btnTest]').click(function(){
var button = this;
setTimeout(function() {
$(button).attr('disabled', 'disabled');
}, 100);
});
Try to use jQuery class selector:
Add CssClass="MyButton" to your ASP.NET button;
Use this selector in jQuery
Set disabled="disabled" attribute on click
jQuery:
$('button.MyButton').click(function(){
$(this).attr('disabled', 'disabled');
});
The sample code is using the ends-with selector. There is no mistake in selector.
you just need to change the code like this
$('[id$=btnTest]').click(function () {
$('[id$=btnTest]').attr('disabled', true);
});
I have tested this and works fine without any issues.
I can fix your problems:$(".classButton").prop('disabled','disabled');
and remove disabled: $(".classButton").prop('disabled', '');
Wouldn't you just need to do the following:
btnTest.Enabled = False;
in the code-behind file? This will cause a postback but it should work.
It wouldn't work because the generated HTML id is different than the ASP.NET id.
So btnTest will be rendered as another Id.
A quick dirty way is to to run the page, view the HTML source and locate the button's generated Id and pass it as an arugment in the jQuery function.
A better way is to generate the jQuery function through code behind:
Literal1.Text = "$('[id$=" + btnTest.ClientId + "]').click(function(
{$(this).attr('disabled', 'disabled');});";
Edit:
Also I couldn't help but realize that your OnClick attribute should point to btnTest_Click and not btn_Click
I have a problem with the following code in an ASPX page:
<script type="text/javascript">
$(document).ready(function() {
$('.test').click(function() {
alert("click")
})
});
</script>
<asp:CheckBox runat="server" Text="Checkbox XYZ" CssClass="test" ID="cb1" />
In the browser (FF3.5 / IE8) I have the following problem:
if I click the checkbox (the small square), it works as expected
if I click the checkbox's text ("Checkbox XYZ"), then the click event is fired twice, and the alert is shown twice.
I guess this has to do with the way the checkbox is rendered to HTML, which is like this:
<span class="test">
<input id="ctl00_c1_cb1" type="checkbox" name="ctl00$c1$cb1" checked="checked"/>
<label for="ctl00_c1_cb1">Checkbox XYZ</label>
</span>
How do I correctly setup the click event handler to prevent it from being called twice?
I have just experienced the same thing, but am not sure that event bubbling is causing my issue. I have a custom tree control, and when an item is opened, I use $(id).click() to attach a handler to all elements of a certain kind.
I suspect that this means that existing items elsewhere that already have the event, may then have it added again. I found that unbinding everything then re-binding solved my problem, thus:
$('img.load_expand').unbind("click").click(function()
{
// handler
});
I think it's because a <label> with a for attribute raises the click event of <input type="radio"> or <input type="checkbox"> element that is associated for when clicked.
So in your jQuery code, you set up a click event handler for both the <label> and the <input> inside <span class="test">. When clicking on the <label>, the click event handler that you set up on the label will execute, then the click event handler set up on the <input> will execute when the label raises the click event on the <input>.
$(document).ready(function() {
$('.test').click(function(event) {
event.stopImmediatePropagation();
alert("Click");
})
}
);
I was able to get my code working by stopping the event Propagation. It did not affect the status change of the checkbox.
Well after reading my question again, I found a way how to solve it.
Just add "input" to the jQuery selector:
<script type="text/javascript">
$(document).ready(function() {
$('.test input').click(function() {
alert("click")
})
});
</script>
Just use .mouseup rather than .click
What you are seeing is event bubbling. The click event is first handled by the label and is then passed on to the checkbox. You get one alert for each. To prevent event bubbling you need to return false in your click handler.
$(document).ready(function() {
$('.test').click(function() {
alert("Click");
return false;
})
});
However while this prevents event bubbling it also has the undesirable side effect of preventing the checkbox from changing state. So you'll need to code around that.
Solved: this to work with Firefox 3.6.12 and IE8.
$(function(){
$("form input:checkbox").unbind("click")
.click(function(){
val = $(this).val();
alert(val);
})
}
The trick is to unbind("click"). before bind it to .click(fn); this will disabled the same event to fire twice.
Note that event "change" will not tricker at first time checkbox has been checked. So I use "click" instead.
I ran into the same issue with a click event, and found this article. In essence, if you have more than one jQuery document-ready functions inside the
<body></body>
tags, you can get multiple events. The fix is, of course, to not do that, or to unbind the click event and rebind it, as noted above. Sometimes, with multiple javascript libraries, it can be hard to avoid multiple document.ready()'s, so the unbind is a good workaround.
<code>
$('#my-div-id').unbind("click").click(function()
{
alert('only click once!');
}
</code>
I know the question is far closed now, but I just have faced the same problem and I want to add the solution I found, may come in handy for similar problems on the future.
When you add ASP code like:
<asp:CheckBox runat="server" Text="Checkbox XYZ" CssClass="test" ID="cb1" />
the problem is that <asp:CheckBox ...> is not an html control, it's just something ASP made up from the twisted mind of some psycho invented, so the browser will receive something else.
The browser will receive something like:
<span class="test">
<input id="garbageforYourId_cb1" type="checkbox" name="garbage$moregarbage$cb1"/>
<label for="evenMoreGarbage_cb1">Checkbox XYZ</label>
</span>
One of many possible solutions:
The browser receive a span which content an input "checkbox" and a label for it with your text. Therefore my solution for this would be something like:
$('.test > :checkbox').click(function() {
if ($(this).attr("checked")) {
alert("checked!!!");
} else {
alert("non checked!!!");
}
});
What happened up there? This selector $('.test > :checkbox') means: find the elements with the class "test" and bring any checkbox that it contains.
The function runs twice. Once from the inside and then it gets called again from inside itself. Simple add a return statement at the end.
<script type="text/javascript">
$(document).ready(function() {
$('.test').click(function() {
alert("click");
return false;
})
});
</script>
<asp:CheckBox runat="server" Text="Checkbox XYZ" CssClass="test" ID="cb1" />
This worked perfectly for me.
I had the same problem with the selector. And end up using off() function.
$('body').off('click').on('click', '<your selector>', function(){
// Your code
});
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;
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