<input type=text>
with focusout
event handler<button>
with click event handlerFocusout checks whether format in input box is correct. It does so by testing input value against a regular expression. If it fails it displays a message (a div
fades-in and -out after some time) and refocuses my input by calling
window.setTimout(function() { $(this).focus(); }, 10);
since I can't refocus in focusout
event handler. focusout
event can't be cancelled either. Just FYI.
Click collects data from input elements and sends it using Ajax.
When user TABs their way through the form everything is fine. When a certain input box failes formatting check it gets refocused immediately after user presses TAB.
But when user doesn't use TAB but instead clicks on each individual input field everything works fine until they click the button
. focusout
fires and sets time-out for refocusing. Since time-out is so short focusing happens afterwards and then click
event fires and issues an Ajax request.
I have implemented my formatting check as an independent jQuery plugin that I want to keep that way. It uses .live()
to attach focusout
on all input fields with a particular attribute where format regular expression is defined.
Data submission is also generic and I don't want to make it dependant on formatting plugin. They should both stay independent.
How can I prevent click event from executing without making these two plugins dependant?
After some searching I've seen that all major browser support document.activeElement
but I can't make it work in Chrome. FF and IE both report this
being the active element, but Chrome always says it's BODY
that is active even though click
fired on the button
element.
Check this code http://jsfiddle.net/Anp4b/1/ and click on the button. Test with Chrome and some other browser and see the difference.
You could use a flag...
Live demo: http://jsfiddle.net/Anp4b/4/
So your question is:
How can I prevent click event from executing without making these two plugins dependent?
Well, you obviously cannot prevent the click event. If the user wants to click the button, he will, and the click event will trigger. There's nothing you can do about that.
So the answer to the above question is: You cannot.
Based on the current conditions, you have to - inside the click handler - retrieve the validation result, and based on that result, decide if form submission should or should not occur.
JS Code:
$("#Name").focusout(function(){
var that = this;
valid = this.value.length ? true : false;
!valid && window.setTimeout(function() {
$(that).focus();
}, 0);
});
$("#Confirm").click(function(e) {
if ( !valid ) { return false; }
e.preventDefault();
alert('AJAX-TIME :)');
});
HTML Code:
<input type="text" id="Name">
<button id="Confirm">OK</button>