Using jQuery Autocomplete with Validator onBlur timing problem - jquery-validate

Here's my problem, I have an input element in a form that is implementing jQuery.Autocomplete and jQuery.validate, all working normally except when I click an element in the autocomplete list to select it.
What happens is validation occurs before the autocomplete sets its value. Because validation occurs on onBlur, and you just clicked an item in the autocomplete list, blur fires and validation occurs a split second before the input is filled with its new value.
I wouldn't mind a double-validation if it was client side, but I happen to be executing an expensive remote ajax validation on this field, so I'd really like to solve this the right way.
My first thought is to proxy all validation onBlur events through a function that times out 10ms later, essentially flip flopping the event order. But, I think, that means tearing into the jQuery.Validate.js code, which I'd rather not do.
Any ideas?

I was able to get this working but perhaps not as elegantly as I would have liked. Ideally I would have liked to call the prototype or defaults version of of onfocusout from within a timeout closure but I wasn't able to figure out how to reference it from that scope.
The approach that I took instead was to override the onfocusout method with its code copy/pasted into a timeout closure. The only other tweak was to change references from this to _this to work within the different scope of the timeout closure.
$("#aspnetForm").validate({
success: "valid",
onkeyup: "false",
onfocusout:
function(element) {
//Delay validation so autocomplete can fill field.
var _this = this;
setTimeout(function() {
if (!_this.checkable(element) && (element.name in _this.submitted || !_this.optional(element)))
_this.element(element);
_this = null;
}, 250);
}
});
Feel free to post improvements.

Related

Fullcalendar Problems w/ filtering Events in agendaDay-View (works only one time, then no more events exist)

I have a problem with filtering events:
I use fullcalender in agendaDay-View
I use a drop-Down list to select a driver
I compare the name (it is a property of event-object) with the selected value
(this part is ok)
Then,
I remove all Events (.fullCalendar('removeEvents');)
Add the specific events
(add with renderEvents doesn't work proberly at the moment)
And now my problem appears:
For the first time it works, however, when I select another 'driver', the events are gone, because of the 'removeEvents'-Action before.
So, how can I solve this problem, that I can only display the filtered events and keep the other (actualley all events) to filter again for second, third n- time?
$('#' + id).fullCalendar('refetchEvents');
was the first idea, however, its brings all back and selected Issues were doubled (and so on).
I'm thankful for every hint.
Ok I think you can solve your problem with fullCalendar's eventRender function.
The function can also return false to completely cancel the rendering of the event.
Your event from events.json should have a property like 'driver_id'.
I would have select field instead of dropdown with option keys being driver ids, values - names or whatever. Lets say it's id would be 'driver_select'.
Then render events like this:
$('#calendar').fullCalendar({
//...
eventRender: function(event, element) {
//driver select should have default value assigned or else no events will be rendered
if ($("#driver_select").val() !== event.driver_id) {
return false; //do not render other driver events
}
}
//...
});
Handle select changes to update
$("#driver_select").off('change').on('change', function() {
$("#calendar").fullCalendar( 'refetchEvents' );
});
Another approach would be to show all drivers in a timeline. For that you can use FullCalendar Scheduler.

what is right jQuery event for a input field with timepicker

I have a input field that is formatted with the data-format HH:mm:ss PP. When the timepicker is clicked the focus on the input field don't appear that's why I couldn't use onblur event. What i want is like keydown or keyup event but it seems doesn't work in my case because focus is out in the input field so what jQuery event should i used?
change seems to work fine:
Fiddle
$("#datepicker").datepicker()
.on("change", function () {
console.log("Changed");
});
Example is with datepicker(), I'm not sure what your timepicker implementation is as it's not in the jquery(ui) api. But it should work as well.
Edit: after looking at the datetimepicker you are using, based on the DOM I'm seeing as a result of datetimepicker() - I think this should work for you:
Fiddle
$('#datetimepicker1').closest(".well").next(".bootstrap-datetimepicker-widget").on("click", "*", function () {
console.log("Changed");
});
Just make sure this is after your datetimepicker() call. Note that this will be triggered on any click within your calendar/time picker even if it is a click on something that is already selected (no change).
If you want, you could store the last value of your input and then check that if it changed before continuing with this event callback function. If it did change, be sure to update the variable you are holding the "last value" in... something like this.
If possible, the best option would actually be to modify datetimepicker()'s js to call a function or trigger an event from the same place it updates the text input. Looking at the code:
set: function () {
var formatted = "";
if (!this._unset) formatted = this.formatDate(this._date);
if (!this.isInput) {
if (this.component) {
var input = this.$element.find("input");
input.val(formatted);
input.trigger("change"); // added this
this._resetMaskPos(input)
}
this.$element.data("date", formatted)
} else {
this.$element.val(formatted);
this.$element.trigger("change"); //added this
this._resetMaskPos(this.$element)
}
},
With the two lines I added above, you should be able to rely on a change event bound to the input element.

jQuery — trigger a live event only once per element on the page?

Here's the scenario
$("p").live('customEvent', function (event, chkSomething){
//this particular custom event works with live
if(chkSomething){
doStuff();
// BUT only per element
// So almost like a .one(), but on an elemental basis, and .live()?
}
})
Here's some background
The custom event is from a plugin called inview
The actual issue is here http://syndex.me
In a nutshell, new tumblr posts are being infnitely scrolled via
javascript hack (the only one out there for tumblr fyi.)
The inview plugin listens for new posts to come into the viewport, if the top of an image is shown, it makes it visible.
It's kinda working, but if you check your console at http://.syndex.me check how often the event is being fired
Maybe i'm also being to fussy and this is ok? Please let me know your professional opinion. but ideally i'd like it to stop doing something i dont need anymore.
Some things I've tried that did not work:
stopPropagation
.die();
Some solutions via S.O. didnt work either eg In jQuery, is there any way to only bind a click once? or Using .one() with .live() jQuery
I'm pretty surprised as to why such an option isnt out there yet. Surely the .one() event is also needed for future elements too? #justsayin
Thanks.
Add a class to the element when the event happens, and only have the event happen on elements that don't have that class.
$("p:not(.nolive)").live(event,function(){
$(this).addClass("nolive");
dostuff();
});
Edit: Example from comments:
$("p").live(event,function(){
var $this = $(this);
if ($this.data("live")) {
return;
}
$this.data("live",true);
doStuff();
});
This one works (see fiddle):
jQuery(function($) {
$("p").live('customEvent', function(event, chkSomething) {
//this particular custom event works with live
if (chkSomething) {
doStuff();
// BUT only per element
// So almost like a .one(), but on an elemental basis, and .live()?
$(this).bind('customEvent', false);
}
});
function doStuff() {
window.alert('ran dostuff');
};
$('#content').append('<p>Here is a test</p>');
$('p').trigger('customEvent', {one: true});
$('p').trigger('customEvent', {one: true});
$('p').trigger('customEvent', {one: true});
});
This should also work for your needs, although it's not as pretty :)
$("p").live('customEvent', function (event, chkSomething){
//this particular custom event works with live
if(chkSomething && $(this).data('customEventRanAlready') != 1){
doStuff();
// BUT only per element
// So almost like a .one(), but on an elemental basis, and .live()?
$(this).data('customEventRanAlready', 1);
}
})
Like Kevin mentioned, you can accomplish this by manipulating the CSS selectors, but you actually don't have to use :not(). Here's an alternative method:
// Use an attribute selector like so. This will only select elements
// that have 'theImage' as their ONLY class. Adding another class to them
// will effectively disable the repeating calls from live()
$('div[class=theImage]').live('inview',function(event, visible, visiblePartX, visiblePartY) {
if (visiblePartY=="top") {
$(this).animate({ opacity: 1 });
$(this).addClass('nolive');
console.log("look just how many times this is firing")
}
});
I used the actual code from your site. Hope that was okay.

How to mimic stopPropagation using jQuery.live

So I know that one of the downsides of using jQuery.live is the unavailability of .stopPropagation(). But I need it badly.
Here's my use case. I have a checkbox is that is currently bound to a click. However, other checkboxes appear on-screen via an AJAX call, meaning I really need .live('click', fn). Unfortunately, the checkbox is situated atop another clickable element, requiring .stopPropagation(). This works fine with .bind('click', fn), but the inability to use it with .live() is hampering me. Using return false doesn't work as the checkbox will not be checked.
Any ideas on how to mimic .stopPropagation() when using .live() without returning false?
Instead of binding a .live handler to the checkboxes, bind a smarter event handler to the container, with behaviour dependent on which element is the target of the event.
$("#container").click(function(e) {
var ele = e.target;
if(ele.tagName.toLowerCase() == 'input'
&& ele.type.toLowerCase() == 'checkbox') {
e.stopPropagation();
// do something special for contained checkboxes
// e.g.:
var val = $(ele).val();
}
});
Here is something of an example to show how this can be used.

Event removal in Mootools, and syntax of event addition

So I have been adding my events thusly:
element.addEvent('click', function() {
alert('foobar');
});
However, when attempting to remove said event, this syntactically identical code (with "add" switched to "remove") does not work.
element.removeEvent('click', function() {
alert('foobar');
});
I assume this is because the two functions defined are not referenced the same, so the event is not technically removed. Alright, so I redefine the event addition and removal:
element.addEvent('click', alert('foobar'));
element.removeEvent('click', alert('foobar'));
Which works great, except now when the page loads, the click event is fired even before it's clicked!
The function is removed, though, which is great......
update: when you do .addEvent('type', function(){ }) and .removeEvent('type', function(){ }), even though the functions may have the same 'signatures', they are two separte anonymous functions, assigned on the fly. function 1 is !== to function 2 - hence there is no match when MooTools tries to remove it.
to be able to remove an exact handler, o:
function handler(){ ... }
el.addEvent('click', handler);
// .. later
el.removeEvent('click', handler);
Internally, events are actually a map of keys to functions in element storage. have a look at this fiddle i did a while back for another SO question - http://www.jsfiddle.net/mVJDr/
it will check to see how many events are stacked up for a particular event type on any given element (or all events).
similarly, removeEvent looks for a match in the events storage - have a look on http://jsfiddle.net/dimitar/wLuY3/1/. hence, using named functions like Nikolaus suggested allows you to remove them easily as it provides a match.
also, you can remove events via element.removeEvents("click") for all click events.
your page now alerts because you pass on alert as the function as well as execute it with the params 'foobar'. METHOD followed by () in javascript means RUN THE METHOD PRECEDING IT IMMEDIATELY, NOT LATER. when you bind functions to events, you pass the reference (the method name) only.
to avoid using an anonymous function and to pass argument,s you can do something like:
document.id('foobar').addEvent('click', alert.bind(this, 'foo'));
as bind raps it for you, but removing this will be even more complicated.
as for event delegation, it's:
parentEl.addEvents({
"click:relay(a.linkout)": function(e, el) {
},
"mouseover:relay(li.menu)": function(e, el) {
}
});
more on that here http://mootools.net/docs/more/Element/Element.Delegation#Element:removeEvent
keep in mind it's not great / very stable. works fine for click stuff, mouseenter is not to be used delegated, just mouseover - which means IE can fire mouseout when it should not. the way i understand it, it's coming improved in mootools 2.0
edit updating to show an example of bound and unbound method within a class pattern in mootools
http://www.jsfiddle.net/wmhgw/
var foo = new Class({
message: "hi",
toElement: function() {
return this.element = new Element("a", {
href: "http://www.google.com",
text: "google",
events: {
"click": this.bar.bind(this), // bind it
"mouseenter": this.bar // unbound -> this.element becomes this
}
});
},
bar: function(event) {
event.stop();
// hi when bound to class instance (this.message will exist)
// 'undefined' otherwise.
console.log(this.message || "undefined");
}
});
document.id(new foo()).inject(document.body);
the mouseenter here will be unbound where this will refer to the default scope (i.e the element that triggered the event - the a href). when bound, you can get the element via event.target instead - the event object is always passed on to the function as a parameter.
btw, this is a slightly less familiar use of class and element relation but it serves my purposes here to illustrate binding in the context of classes.
assig the function to a variable and use the same reference to add and remove the event.
if you use an anonymous function you will get to different references
var test = function(){ alert('test: ' + this.id); }
$('element').addEvent('click', test);
...
$('element').removeEvent('click', test);
addEvent : Attaches an event listener to a DOM element.
Example -
$('myElement').addEvent('click', function(){
alert('clicked!');
});
removeEvent : Works as Element.addEvent, but instead removes the specified event listener.
Example -
var destroy = function(){ alert('Boom: ' + this.id); } // this refers to the Element.
$('myElement').addEvent('click', destroy);
//later...
$('myElement').removeEvent('click', destroy);
This means when you add an event with a eventhandler not an anonymous function if you than remove the event than it will be removed.

Resources