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