ASP.Net Client Events on DropDownList? - asp.net

Is there a client event that I can use for when a DropDownList's data has been loaded/bound onto the control? I need to trigger event on their side when this happens.
Basically, I am trying to lock out the controls while the data is being loaded as if there is a slowdown (not uncommon) a user can start inputting data and then lose focus as they are typing.
I tried doing this in the tags but the methods located there seem to stop working after the first postback! (Any help there would be greatly appreciated). As a workaround I tried attaching the events to the elements themselves and while this works for locking, using the onchange event, I am unable to unlock it upon the data successfully loading!
Any ideas? Thanks for the answers so far :)

Since data will be bound on the server side, you don't have a client-side event for that specific event, however, one the page has rendered, the data will be there, so you may want to run your client script in the document.load event, or using something like jQuery's document.ready event. That will trigger your script to run once the page (including your bound drop down) is finished loading.

Jason is correct here in that you cannot "notify" the client when such an event occurs. One thing you could do, is call the Page.RegisterStartupScript() method to do something with JavaScript once the page has finished loading (and assumedly that the post back that has done your databinding has occurred). Again, this assumes that you want to do something on the client side once the data binding is complete, as opposed to server side.

Are you able to use ASP.NET AJAX in your application? If so, you can have the selected event open up a modal dialog in which you can display your "processing" text while you are populating the drop down list. That way the user does not have access to any other controls and you can do what you need without worry.

i use the following code in my master pages for my websites. This stops the user from attempting to use a control before its completely bound. I have found that if a control hasn't been completely bound (slow connections) then the page blows up.
Essentially the script hijacks the post back if that page isn't done. Allowing the user to not do anything until the page has finished processing. I wrote this a year ago and its come in very handy.
first set the onload body tag to setdopostback()
add this in a scrip block in the body.
var boolDoPostBack = false;
if (__doPostBack)
{
// save a reference to the original __doPostBack
var __oldDoPostBack = __doPostBack;
//replace __doPostBack with another function
__doPostBack = AlwaysFireBeforeFormSubmit;
}
function setdopostback()
{
boolDoPostBack = true;
}
function AlwaysFireBeforeFormSubmit (eventTarget, eventArgument)
{
var x= document.readyState
if (x != "complete")
{
if (x == "loading" || x == "interactive" || x == "unitialized" || x == "loaded")
{
//do nothing with IE postback
}
else if (!boolDoPostBack)
{
//do nothing with FireFox postback
}
else
{
//alert('Allow Postback 1');
return __oldDoPostBack (eventTarget, eventArgument);
}
}
else
{
//alert('Allow Postback 2');
return __oldDoPostBack (eventTarget, eventArgument);
}
}

Related

bootstrap studio: enter key appears to causing reload of page

I have a web page with several forms. Only one is visible at a time, depending on state.
On one form, pressing the enter key appears to be causing a reload of the page rather than triggering a click event for the form's button.
I have a lot of javascript, primarily because I need client side interaction with mailchimp. Because of that, I have disabled the form's action= html and have instead created a javascript function to handle the click. It works fine if you click on the button.
I have also assigned a listener for the sole field in the form:
var input = document.getElementById ("new-email-address");
input.addEventListener ("keyup", function(event)
{
if (event.keyCode === 13)
{
event.preventDefault();
document.getElementById("new-email-address").click();
}
});
Yet, when I click the enter key, the $(document).ready (function() executes. It's possible something else is executing beforehand, but, if so, I haven't found a way to discover that.
What could be causing this behavior ?
It turns out that the enter key is being handled at the form level. To disable that, I added this code for each form:
$("#the-form").keypress(function(e)
{
if (e.which == 13) // Enter key
return false;
});

Confirm DropDownList selected value

I want to show the user a confirm dialog when he tries to change the selected item of a DropDownList. If the selection is confirmed i want to execute some server side code.
Say, DDL has values 1 and 2.
Value 1 is selected (default).
The user selects Value 2. A confirm dialog appears.
If the user selects 'Yes', then the selected item changes. Some server side code must be executed.
If the user selects 'No' then the selected item is reverted back to Value 1. No server side code executed.
I'm having a lot of trouble with this one, since DDL has few events to use.
So far i got
this.MyDropDown.Attributes["onChange"] = #"return confirm('Are you sure?');";
and a event handler for the SelectedIndexChanged event of the DDL for the server side code.
But i'm having trouble with the fact that i can't neither stop (or revert) the item being changed nor the SelectedIndexChanged event being fired.
Any suggestions?
The reason it's not triggering the server side event is because you're wiping out the built-in webforms event handler that would trigger the post back. As for reverting the value, you'll need to save it and then reload it.
add this javascript function
function handleChange(opt) {
if (!confirm('are you sure')) {
opt.selectedIndex = opt.oldIndex;
}
else {
__doPostBack('MyDropDown','')
}
}
and set the client side events like so
this.MyDropDown.Attributes["onChange"] = "handleChange(this)";
this.MyDropDown.Attributes["onFocus"] = "this.oldIndex = this.selectedIndex";
This is complete solution, as i have already used it. Just refer the following instructions:
// Paste it in Aspx file
function handleChange(opt) {
if (!confirm('Are you sure?')) {
opt.selectedIndex = opt.oldIndex;
}
else {
__doPostBack('MyDropDown','')
}
}
Paste this in Page Load event outside IsPostBack:
this.MyDropDown.Attributes["onChange"] = "handleChange(this)";
this.MyDropDown.Attributes["onFocus"] = "this.oldIndex = this.selectedIndex";
Note: Set AutoPostBack Proerty False of Dropdownlist.

Jquery function calls more than one time

I am having an aspx page in which I am calling a user control. The user control I am using a pop up to display it when a user clicks a asp:linkbutton. In that user control I am having a textbox and I am calling a Jquery Blur to do some validation. While doing so the function is calling [blur] is calling twice. I just called an alert() with the textbox value.So I can see the alert is coming twice .What I need to do to avoid the second time. I need to do it only whenever the user going out of the textbox and that also one time.
$('#<%=txtCategory.ClientID %>').blur(function() {
alert($(this).val());
});
This is called twice.Thanks for ur response.
Try this one.
$("input:text[id$='txtCategory']").blur(function() {
alert($(this).val());
});
are you using live event handler by any chance. if that is the case change it to bind blur.
Also if obj is the jquery object that you are trying to beind the blur event on you can add this code
if (obj .data("events") === null || obj .data("events") === undefined || obj
.data("events").click === undefined)
{
function(){bind blur);
}

Validation controls are not validating on enabling on client side using JavaScript

As per requirement I disabled all validation controls in page on PageLoad event in server side.
On clicking submit button I want to activate them and validate the page and if the page is okay submit other wise not.
I am able to enable all validaters but one thing that I am unable to understand is that they do not validate the page. I set alerts and check they are being enabled but they do not validate the page and let the page submit.
I am sorry I couldn't get where I am wrong, may be there need to call some validation method as well or I should prevent default behavior of button. Please guide me.
Below is my script:
<script type="text/javascript">
function NextClicked() {
var _ddlStatus = document.getElementById("<%=ddlEmpStatus.ClientID%>");
var _selectedIndex = _ddlStatus.selectedIndex;
if (_selectedIndex == 0) {
alert("Nothing selected");
}<br/>
else<br/>
if (_selectedIndex == 1) {
for (i = 0; i < Page_Validators.length; i++) {
Page_Validators[i].Enabled = true;
}
}
}
</script>
From the server, you have to have them enabled before the button click; otherwise, I think you need to loop through the server-side collection and enable them, plus call their validate() method explicitly.
Or, you can also try the client-side validatorenable method (http://forums.asp.net/t/1175267.aspx) to enable them.
If you disable by setting Enabled = false from the server, you may have issues even using the client-side API altogether. Not sure about that though, just know that can be an issue with other controls.
HTH.

Programmatically triggering events in Javascript for IE using jQuery

When an Event is triggered by a user in IE, it is set to the window.event object. The only way to see what triggered the event is by accessing the window.event object (as far as I know)
This causes a problem in ASP.NET validators if an event is triggered programmatically, like when triggering an event through jQuery. In this case, the window.event object stores the last user-triggered event.
When the onchange event is fired programmatically for a text box that has an ASP.NET validator attached to it, the validation breaks because it is looking at the element that fired last event, which is not the element the validator is for.
Does anyone know a way around this? It seems like a problem that is solvable, but from looking online, most people just find ways to ignore the problem instead of solving it.
To explain what I'm doing specifically:
I'm using a jQuery time picker plugin on a text box that also has 2 ASP.NET validators associated with it. When the time is changed, I'm using an update panel to post back to the server to do some things dynamically, so I need the onchange event to fire in order to trigger the postback for that text box.
The jQuery time picker operates by creating a hidden unordered list that is made visible when the text box is clicked. When one of the list items is clicked, the "change" event is fired programmatically for the text box through jQuery's change() method.
Because the trigger for the event was a list item, IE sees the list item as the source of the event, not the text box, like it should.
I'm not too concerned with this ASP.NET validator working as soon as the text box is changed, I just need the "change" event to be processed so my postback event is called for the text box. The problem is that the validator throws an exception in IE which stops any event from being triggered.
Firefox (and I assume other browsers) don't have this issue. Only IE due to the different event model. Has anyone encountered this and seen how to fix it?
I've found this problem reported several other places, but they offer no solutions:
jQuery's forum, with the jQuery UI Datepicker and an ASP.NET Validator
ASP.NET forums, bug with ValidatorOnChange() function
I had the same problem. Solved by using this function:
jQuery.fn.extend({
fire: function(evttype){
el = this.get(0);
if (document.createEvent) {
var evt = document.createEvent('HTMLEvents');
evt.initEvent(evttype, false, false);
el.dispatchEvent(evt);
} else if (document.createEventObject) {
el.fireEvent('on' + evttype);
}
return this;
}
});
So my "onSelect" event handler to datepicker looks like:
if ($.browser.msie) {
datepickerOptions = $.extend(datepickerOptions, {
onSelect: function(){
$(this).fire("change").blur();
}
});
}
I solved the issue with a patch:
window.ValidatorHookupEvent = function(control, eventType, body) {
$(control).bind(eventType.slice(2), new Function("event", body));
};
Update: I've submitted the issue to MS (link).
From what you're describing, this problem is likely a result of the unique event bubbling model that IE uses for JS.
My only real answer is to ditch the ASP.NET validators and use a jQuery form validation plugin instead. Then your textbox can just be a regular ASP Webforms control and when the contents change and a postback occures all is good. In addition you keep more client-side concerns seperated from the server code.
I've never had much luck mixing Webform Client controls (like the Form Validation controls) with external JS libraries like jQuery. I've found the better route is just to go with one or the other, but not to mix and match.
Not the answer you're probably looking for.
If you want to go with a jQuery form validation plugin concider this one jQuery Form Validation
Consider setting the hidden field _EVENTTARGET value before initiating the event with javascript. You'll need to set it to the server side id (replace underscore with $ in the client id) for the server to understand it. I do this on button clicks that I simulate so that the server side can determine which OnClick method to fire when the result gets posted back -- Ajax or not, doesn't really matter.
This is an endemic problem with jQuery datepickers and ASP validation controls.
As you are saying, the wrong element cross-triggers an ASP NET javascript validation routine, and then the M$ code throws an error because the triggering element in the routine is undefined.
I solved this one differently from anyone else I have seen - by deciding that M$ should have written their code more robustly, and hence redeclaring some of the M$ validator code to cope with the undefined element. Everything else I have seen is essentially a workaround on the jQuery side, and cuts possible functionality out (eg. using the click event instead of change).
The bit that fails is
for (i = 0; i < vals.length; i++) {
ValidatorValidate(vals[i], null, event);
}
which throws an error when it tries to get a length for the undefined 'vals'.
I just added
if (vals) {
for (i = 0; i < vals.length; i++) {
ValidatorValidate(vals[i], null, event);
}
}
and she's good to go. Final code, which redeclares the entire offending function, is below. I put it as a script include at the bottom of my master page or page.
Yes, this does break upwards compatibility if M$ decide to change their validator code in the future. But one would hope they'll fix it and then we can get rid of this patch altogether.
// Fix issue with datepicker and ASPNET validators: redeclare MS validator code with fix
function ValidatorOnChange(event) {
if (!event) {
event = window.event;
}
Page_InvalidControlToBeFocused = null;
var targetedControl;
if ((typeof (event.srcElement) != "undefined") && (event.srcElement != null)) {
targetedControl = event.srcElement;
}
else {
targetedControl = event.target;
}
var vals;
if (typeof (targetedControl.Validators) != "undefined") {
vals = targetedControl.Validators;
}
else {
if (targetedControl.tagName.toLowerCase() == "label") {
targetedControl = document.getElementById(targetedControl.htmlFor);
vals = targetedControl.Validators;
}
}
var i;
if (vals) {
for (i = 0; i < vals.length; i++) {
ValidatorValidate(vals[i], null, event);
}
}
ValidatorUpdateIsValid();
}
This is how I solved a simlar issue.
Wrote an onSelect() handler for the datepicker.
link text
In that function, called __doPostBack('textboxcontrolid','').
This triggered a partial postback for the textbox to the server, which called the validators in turn.

Resources