I'm using jquery-ui datepicker as one of my inputs. If a user blurs from an input, I display a relevant message (e.g. "This field is required"). For this purpose I have the following jQuery, which works perfectly fine for simple <select> and <input type="text"> tags:
$("input").blur(function(){
if($(this).val()=="")
$(this).next().text("This field is required.");
else
$(this).next().text("");
});
However, in case of datepicker (where I have to essentially blur to select a date) the error message gets displayed even after I've selected the date (i.e. selection of date is leading to the blur event). This requires that the .blur(function(){}); should be called after the blur event is completed (not simultaneously).
How to solve this situation?
Here's a DEMO.
You could add your validation check to the onClose event of the datepicker, rather than the blur event of the input field:
$("#datepicker").datepicker({onClose: function(selectedDate) {
if(!selectedDate) {
$(this).next().text("This field is required.");
}
}});
Kind of a hack, but you could just delay the check with setTimeout:
$("input").blur(function () {
var $t = $(this);
setTimeout(function () {
if ($t.val() == "") $t.next().text("This field is required.");
else $t.next().text("");
}, 100);
});
http://jsfiddle.net/D4AGz/96/
Related
i'm working on a web application in mvc and generated textbox with loop so the id of every textbox in unique and on the focusout event of every textbox check the validation through ajax. The problem is focusout event is triggered twice automatically and show twice value of every textbox and pass twice value, i d'ont know what the reason. My code is given below.
Highly Thankful to all of you!
$('#StartTime0').focusout(function () {
if ($(this).val() && $('#EndTime0').val()) {
var MonTime1 = checkTime($(this).val(), $("#EndTime0").val())
if (MonTime1) {
$("#Onelimit0").addClass("hidden");
console.log($(this).val());
console.log($('#EndTime0').val());
//DoctorTimeCheck($(this).val(), $("#EndTime0").val())
}
else {
$("#Onelimit0").removeClass("hidden");
}
}
else {
$("#Onelimit0").addClass("hidden");
}
});
I have a checkout form where a zipcode is needed. I need this zipcode to get a LocationID. The zipcodes are in 0000XX format but i just need the first 4 digits. Now i have made a (global) javascript to get the locationID trough ajax.
The only problem is that now im using a keyup function that is activated when someone types in a zipcode. But i want it to be activated when a user has typed in something and clicks on another field. how can i do this ?
$('#deliveryzip').bind('keyup change', function(){
//Get zip
var zip = $('#deliveryzip').val();
//Strip first 4 chars from input
//check if 4 chars are integer
//if all ok do ajax...
//Get locationID from zipcode
$.post(jssitebaseUrl+'/ajaxFile.php',{"zip":zip,"action":"getLocInfo"},function(response){
if(response == "ok"){
alert(response);
//If return is ok..
var show = true;
}
});
if(show){
$('#locInfo').show();
} else {
$('#locInfo').hide();
}
return false;
});
Instead of listening to the keyup event, why don't you just listen to the change event?
$('#deliveryzip').on('change', function(){....});
The change event fires when an input field changed and once it looses focus (e.g. through the user clicking on another element). See http://msdn.microsoft.com/en-us/library/ie/ms536912(v=vs.85).aspx for more info (from Microsof) and here the documentation from Mozilla https://developer.mozilla.org/en-US/docs/Web/Reference/Events/change
You can use onBlur function : http://www.w3schools.com/jsref/event_onblur.asp
The onblur event occurs when an object loses focus.
Onblur is most often used with form validation code (e.g. when the user leaves a form field).
Tip: The onblur event is the opposite of the onfocus event.
With jQuery : on( "blur", handler )
Change 'keyup change' to blur
Blur is essentially the opposite of focus
Documentation here
Requirement:
I'd like a jQuery autocomplete element that allows the user to pick an item and set the display field and a hidden field with the selected value. But I would also like the field and the hidden field to be cleared when the input field receives focus by the user.
Problem:
The problem I'm facing is that when the user selects an item it's almost like jQuery is executing the onSelect function and then sending the focus to the input field again which fires my focus() event (and therefore clearing my selection).
Problem Browser:
IE8 , works in Chrome. Did not try others.
Attempted fixes:
I have tried setting the focus to another element in the select()
function. It did put the focus on that element but only after
focussing on the input field
Tried both event.preventDefault() and event.stopPropagation() in the
select() method. Did not work.
Blur didnt work either.
Workarounds:
I guess I can change the clearing to be on click instead of on focus, but this is not what I want.
Similar stackoverflow thread:
jquery autocomplete remove focus after suggest
Code:
Here is my code:
$(function () {
$("#autosuggest").autocomplete({
source: "my server path",
minLength: 3,
select: function (event, ui) {
if (ui.item) {
$("#autosuggest").val(ui.item.value);
$("#hidden").val(ui.item.id);
}
}
});
$("#autosuggest").focus(function () {
$("#hidden").val("");
this.value = "";
});
});
The problem is: when you click on an autocomplete suggestion, the focus shifts to that dropdown menu, ever so shortly, to return to your input afterwards. Do you still get this problem if you choose the autocomplete suggestion by using the arrow-down button? If you do not, then this is the problem.
The only way I can see to fix this is not to make it a focus event after all, but I think I know why you don't want to make it a click event: you also want to capture tabbing into the field.
Solution: make it a click handler, and add a 'keyup' handler that executes the click handler handler if the key was a tab (arrow-down etc are still allowed).
I got this from the jQuery forum and it works fabulous!
select: function(event, ui) {
$(event.target).autocomplete("close")
setTimeout(function() {
$(event.target).blur();
})
}
Link: https://forum.jquery.com/topic/autocomplete-input-field-stays-focused-after-selection
Try onSelect function..
$(function () {
$("#autosuggest").autocomplete({
source: "my server path",
minLength: 3,
select: function (event, ui) {
if (ui.item) {
$("#autosuggest").val(ui.item.value);
$("#hidden").val(ui.item.id);
}
},
onSelect: function (suggestion) {
$(this).click();}
});
$("#autosuggest").focus(function () {
$("#hidden").val("");
this.value = "";
});
});
I have a pretty simple form. When the user types in an input field, I want to update what they've typed somewhere else on the page. This all works fine. I've bound the update to the keyup, change and click events.
The only problem is if you select an input from the browser's autocomplete box, it does not update. Is there any event that triggers when you select from autocomplete (it's apparently neither change nor click). Note that if you select from the autocomplete box and the blur the input field, the update will be triggered. I would like for it to be triggered as soon as the autocomplete .
See: http://jsfiddle.net/pYKKp/ (hopefully you have filled out a lot of forms in the past with an input named "email").
HTML:
<input name="email" />
<div id="whatever"><whatever></div>
CSS:
div {
float: right;
}
Script:
$("input").on('keyup change click', function () {
var v = $(this).val();
if (v) {
$("#whatever").text(v);
}
else {
$("#whatever").text('<whatever>');
}
});
I recommending using monitorEvents. It's a function provide by the javascript console in both web inspector and firebug that prints out all events that are generated by an element. Here's an example of how you'd use it:
monitorEvents($("input")[0]);
In your case, both Firefox and Opera generate an input event when the user selects an item from the autocomplete drop down. In IE7-8 a change event is produced after the user changes focus. The latest Chrome does generate a similar event.
A detailed browser compatibility chart can be found here:
https://developer.mozilla.org/en-US/docs/Web/Events/input
Here is an awesome solution.
$('html').bind('input', function() {
alert('test');
});
I tested with Chrome and Firefox and it will also work for other browsers.
I have tried a lot of events with many elements but only this is triggered when you select from autocomplete.
Hope it will save some one's time.
Add "blur". works in all browsers!
$("input").on('blur keyup change click', function () {
As Xavi explained, there's no a solution 100% cross-browser for that, so I created a trick on my own for that (5 steps to go on):
1. I need a couple of new arrays:
window.timeouts = new Array();
window.memo_values = new Array();
2. on focus on the input text I want to trigger (in your case "email", in my example "name") I set an Interval, for example using jQuery (not needed thought):
jQuery('#name').focus(function ()
{
var id = jQuery(this).attr('id');
window.timeouts[id] = setInterval('onChangeValue.call(document.getElementById("'+ id +'"), doSomething)', 500);
});
3. on blur I remove the interval: (always using jQuery not needed thought), and I verify if the value changed
jQuery('#name').blur(function ()
{
var id = jQuery(this).attr('id');
onChangeValue.call(document.getElementById(id), doSomething);
clearInterval(window.timeouts[id]);
delete window.timeouts[id];
});
4. Now, the main function which check changes is the following
function onChangeValue(callback)
{
if (window.memo_values[this.id] != this.value)
{
window.memo_values[this.id] = this.value;
if (callback instanceof Function)
{
callback.call(this);
}
else
{
eval( callback );
}
}
}
Important note: you can use "this" inside the above function, referring to your triggered input HTML element. An id must be specified in order to that function to work, and you can pass a function, or a function name or a string of command as a callback.
5. Finally you can do something when the input value is changed, even when a value is selected from a autocomplete dropdown list
function doSomething()
{
alert('got you! '+this.value);
}
Important note: again you use "this" inside the above function referring to the your triggered input HTML element.
WORKING FIDDLE!!!
I know it sounds complicated, but it isn't.
I prepared a working fiddle for you, the input to change is named "name" so if you ever entered your name in an online form you might have an autocomplete dropdown list of your browser to test.
Detecting autocomplete on form input with jQuery OR JAVASCRIPT
Using: Event input. To select (input or textarea) value suggestions
FOR EXAMPLE FOR JQUERY:
$(input).on('input', function() {
alert("Number selected ");
});
FOR EXAMPLE FOR JAVASCRIPT:
<input type="text" onInput="affiche(document.getElementById('something').text)" name="Somthing" />
This start ajax query ...
The only sure way is to use an interval.
Luca's answer is too complicated for me, so I created my own short version which hopefully will help someone (maybe even me from the future):
$input.on( 'focus', function(){
var intervalDuration = 1000, // ms
interval = setInterval( function(){
// do your tests here
// ..................
// when element loses focus, we stop checking:
if( ! $input.is( ':focus' ) ) clearInterval( interval );
}, intervalDuration );
} );
Tested on Chrome, Mozilla and even IE.
I've realised via monitorEvents that at least in Chrome the keyup event is fired before the autocomplete input event. On a normal keyboard input the sequence is keydown input keyup, so after the input.
What i did is then:
let myFun = ()=>{ ..do Something };
input.addEventListener('change', myFun );
//fallback in case change is not fired on autocomplete
let _k = null;
input.addEventListener( 'keydown', (e)=>_k=e.type );
input.addEventListener( 'keyup', (e)=>_k=e.type );
input.addEventListener( 'input', (e)=>{ if(_k === 'keyup') myFun();})
Needs to be checked with other browser, but that might be a way without intervals.
I don't think you need an event for this: this happens only once, and there is no good browser-wide support for this, as shown by #xavi 's answer.
Just add a function after loading the body that checks the fields once for any changes in the default value, or if it's just a matter of copying a certain value to another place, just copy it to make sure it is initialized properly.
I'm after the following functionality:
user clicks on or tabs into a textbox
all text in the textbox is selected, unless the textbox already had focus, in which case the default clicking/selecting functionality should occur
Is this possible?
This works in Firefox 5
$('input[type="text"]').live('focus', function () {
this.select();
});
http://jsfiddle.net/HmQxZ/13/
Chrome and IE8 selects all the text for only a split second
This works* in Chrome
$('input[type="text"]').live('click', function () {
this.select();
});
http://jsfiddle.net/HmQxZ/12/
Firefox and IE8 selects all text but upon subsequent clicking, the text remains selected.
*kind of works, after textbox has focus, clicking on it alternates between selecting all text and being able to click where the blinking caret goes. This is probably acceptable.
Just delay it by a millisecond with setTimeout:
$('input[type="text"]').live('focus', function() {
var inp = this;
setTimeout(function() {
inp.select();
}, 1);
});
http://jsfiddle.net/HmQxZ/14/
What's happening is some other browser event is setting the selection after you've selected the text. So, by waiting a millisecond, you let all the browser events finish, and then select the text. Nothing will undo it now.
You may want to add
event.preventDefault();
return false;
to your function (the first one). That may fix the other browsers.
Also, add event to the function sig:
$('input[type="text"]').live('focus', function (event) {
If you can use jQuery then you can do something like;
$("#myInputField").focus(function(){
// Select input field contents
this.select();
});
// Add this behavior to all text fields
$("input[type=text]").focus(function(){
// Select field contents
this.select();
});
Taken from HERE
You should remember to do a return false; event.stopPropagation(); event.preventDefault() like so:
$('input[type="text"]').live('click', function (event) {
this.select();
event.stopPropagation();
event.preventDefault();
return false;
});
http://jsfiddle.net/7rYLV/