Jquery function calls more than one time - asp.net

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);
}

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;
});

How to know which button of User Control is clicked from parent form Asp.net?

I want to capture which button is clicked in page load method of code behind file.
Button is user control button and It does not post back. Since it used by many other forms, I don't want to changes that button.
I tried this
Dim ButtonID As String = Request("btnRefresh.ID")
But it doesn't work.
Is it possible to know without touching in user control and using Javascript?
Thank you
As described here How to check whether ASP.NET button is clicked or not on page load:
The method: Request.Params.Get("__EVENTTARGET"); will work for
CheckBoxes, DropDownLists, LinkButtons, etc.. but this does not work
for Button controls such as Buttons and ImageButtons
But you have a workaround, first of all you have to define a hidden field in the Parent Page. In this field you will store which button inside the user control was clicked using javascript/jquery. And then in your Parent Page Page_Load method you just read the hiddenField.Value property:
JQuery
1) Add listener to every input type submit button:
$(document).ready(function () {
$("input[type=\"submit\"]").on("click", function () {
alert(this.name);
$("#hiddenField1").val(this.name);
});
});
2) [Better one] Add listener to some indentificable div inside the user control and delegate the event to child inputs like this:
$(document).ready(function () {
$("#someElementOfUserControl").on("click", "input[type=\"submit\"]", function () {
alert(this.name);
$("#hiddenField1").val(this.name);
});
});
Javascript
Since everything done with JQuery can be done with Javascript you can do the following (i will not write both samples, just one):
function handleClick(event) {
alert(event.target.name);
document.getElementById("hiddenField1").value = event.target.name;
}
var inputsInUC = document.getElementsByTagName('input');
for (i = 0; i < inputsInUC.length; i++) {
inputsInUC[i].addEventListener('click', handleClick, false);
}
Remember to define this javascript after all your html elements.
EDIT:
Also, for the completeness of the answer let me tell you that the proper way in case you can change the user control behaviour is to use events as described here How do i raise an event in a usercontrol and catch it in mainpage?

Check if ValidationSummary is Valid using OnClientClick

Is there a way to check if a ValidationSummary control has its IsValid property set to true using Javascript in the OnClientClick event of a button?
What I'm trying to do is to show a message that says "please wait while your file is uploading" on an upload page, but if I use javascript to show that message, it shows up even when the ValidationSummary has errors, so the message shows up along with the errors underneath, which confuses users.
If you have several validation groups on single page then you should check only certain group:
var isValid = Page_ClientValidate('GroupName');
I think this will do what you want.
var isValid = false;
if (typeof(Page_ClientValidate) == 'function')
{
isValid = Page_ClientValidate();
}
if(isValid)
{
ShowMessage(...);
}
In case others need something like this, here is my solution:
In the button's OnClientClick event, I'm calling a javascript function called showContent(). In this function, I use setTimeout to call a second function that checks the page's IsValid property:
function showContent()
{
setTimeout("delayedShow()", 1);
}
function delayedShow()
{
if (Page_IsValid != null && Page_IsValid == true)
{
document.getElementById('divUploading').style.display = "block";
}
}
The Page_IsValid returns true in the OnClientClick event because the javascript validation runs after this, so the 1 second delay allows the IsValid property to be properly set.
I guess what you should do is dissable the uppload button and show a message while upload is in progress. For example by using an ajax panel and an progress template.

ASP.Net Client Events on DropDownList?

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);
}
}

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