I created an application to list all products, and user can search for products using different ways, one of them is scanning barcode, usually, user should focus on the search input and scan the barcode, this is working fine.
But when the input (search input) is not focused, I want to make it default so that when user typed something, or scanned barcode, this input get focused before keydown or keypress.
Is that possible? for example if we can get an event before (keydown) or (keypress) then we can focus on the input so easy.
(Same idea if user pasted a text from clip board using control+v the the default search input focused and pasted to it).
You don't need an event before keydown, you can just use keydown:
$(document).bind('keydown',function(e){
$('input').focus();
});
See this jsfiddle example
Yes, it is possible if you add an event listener to the window object.
Example:
jQuery(document).ready(function() {
jQuery(window).keydown(function(ev) {
if (ev.target.tagName === 'INPUT' || ev.target.tagName === 'TEXTAREA')
return;
jQuery('#mydefaulttextbox').focus()
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This is my default input:
<input id="mydefaulttextbox" type="text" />
<p>
This is another input:
<input type="text" />
</p>
The keydown binding is used because the character are only impressed when the keyup or keypress event is received.
You also don't need jQuery for this.
<input type='text' id='bar_code_input' name='bar_code_input' />
<script type='text/javascript'>
document.addEventListener('keypress', function(){
var bc_input = document.getElementById('bar_code_input');
bc_input.focus();
});
</script>
https://jsfiddle.net/5d51z8rr/
When a user tabs through form input boxes it goes in order. I figured out that you could order them though when using tabindex=x. I have 5 inputs on my form, so I have tabindex 5 different times. After that it goes to different items on the page, so is there a way to make it just loop through those 5 items? By the way I can not use tabindex=0 because then I would have to add that to 100s of items. So basically my question is how can I make a so called "tab loop".
You can't declaratively set up a tab loop. That feature is designed to work within the normal tabbing behavior of the browser, which is to visit all tab-able elements in both the page and the browser chrome.
If you want to prevent tabbing away from a chosen subset of elements, you'll need a little JavaScript and you better know very well why you're doing it and what it'll break, give some visual cues that the form is focused to the detriment of the rest of the UI, and think of some non-visual clients for whom keyboard navigation is even more important.
Assuming that you have indeed knowingly judged that it's OK to hijack tabbing, one relatively safe way to do this is to create a dummy tabbable element (has to be displayed, but could be practically invisible) with a tabIndex that makes it the next after the last item in your form, and another right before the first in your form.
dummyItemBeforeForm.addEventListener('focus', function(e){
lastItemOfMySuperImportantForm.focus() }, true )
dummyItemAfterForm.addEventListener('focus', function(e){
firstItemOfMySuperImportantForm.focus() }, true )
That will make the focus loop back to the beginning of the form when tabbing away from the last item, and loop to the end when shift-tabbing from the first.
Make sure that the dummy items are disabled by default and only become focusable once the user focuses your form and gets the visual cues that the form is now kind of modal, and disable the dummies again once the user is done with the form.
And please, please, test this with real users, and see if they like it or if they panic because you broke their expected tab behavior.
I found an easy way to achieve this using jQueryUI. I created a .tabloop class and I'm using the following snippet.
The :tabbable selector is not natively included in jQuery, it's part of jQueryUI but you can easily make your own.
// Focus loop inside element with class tabloop
$(function() {
$(document).on('keydown', '.tabloop :tabbable:not([readonly])', function(e) {
// Tab key only (code 9)
if (e.keyCode != 9)
return;
// Get the loop element
var loop = $(this).closest('.tabloop');
// Get the first and last tabbable element
var firstTabbable = loop.find(':tabbable:not([readonly])').first();
var lastTabbable = loop.find(':tabbable:not([readonly])').last();
// Leaving the first element with Tab : focus the last one
if (firstTabbable.is(e.target) && e.shiftKey == true) {
e.preventDefault();
lastTabbable.focus();
}
// Leaving the last element with Tab : focus the first one
if (lastTabbable.is(e.target) && e.shiftKey == false) {
e.preventDefault();
firstTabbable.focus();
}
});
});
.tabloop {
border: 1px red solid;
padding: 1ch;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<p>
<label for="text1">Field 1:</label>
<input type="text" id="text1">
</p>
<p>
<label for="text2">Field 2:</label>
<input type="text" id="text2">
</p>
<p>
Link
</p>
<p>
<button type="button">Button</button>
</p>
<div class="tabloop">
<p>
<label for="text3">Field 3:</label>
<input type="text" id="text3">
</p>
<p>
<label for="text4">Field 4:</label>
<input type="text" id="text4">
</p>
<p>
Link
</p>
<p>
<button type="button">Button</button>
</p>
</div>
As a follow up to #NicolasBernier JqueryUI answer, this is the code that worked w/o the ':tabbable' keyword.
// first block deals with first tabbable element
$('uniqueContainerOfElementInQuestion').find('firstTabbableElement(ex."a")').first().on('keydown', function (e) {
// first ele w/ shift and tab
if (e.shiftKey == true && e.keyCode == 9) {
console.log('Shift tab on first')
e.preventDefault();
// focus on element
// if it isn't working uncomment out timeout as possible test/quickfix
// setTimeout(()=>{
$('uniqueContainerOfElementInQuestion').find('lastTabbableElement(ex."button")').last().focus();
// })
}
});
$('uniqueContainerOfElementInQuestion').find('lastTabbableElement(ex."button")').last().on('keydown', function (e) {
// Leaving the last element with Tab : focus the first one
if (e.shiftKey == false && e.keyCode == 9) {
console.log('tab on last')
e.preventDefault();
// setTimeout(()=>{
$('uniqueContainerOfElementInQuestion').find('firstTabbableElement(ex."a")').first().focus();
// })
}
});
TLDR
Check this example in chrome.
Type someting and press tab. see one new box appear
type something and press enter. see two new boxes appear, where one is expected.
Intro
I noticed that when using enter rather then tab to change fields, my onchange function on an input field was firing twice. This page was rather large, and still in development (read: numerous other bugs), so I've made a minimal example that shows this behaviour, and in this case it even does it on 'tab'. This is only a problem in Chrome as far as I can tell.
What it should do
I want to make a new input after something is entered into the input-field. This field should get focus.
Example:
javascript - needing jquery
function myOnChange(context,curNum){
alert('onchange start');
nextNum = curNum+1;
$(context.parentNode).append('<input type="text" onchange="return myOnChange(this,'+nextNum+')" id="prefix_'+nextNum+'" >');
$('#prefix_'+nextNum).focus();
return false;
}
HTML-part
<div>
<input type="text" onchange="return myOnChange(this,1);" id="prefix_1">
</div>
the complete code is on pastebin. you need to add your path to jquery in the script
A working example is here on jFiddle
The onchange gets called twice: The myOnChange function is called, makes the new input, calls the focus(), the myOnChange gets called again, makes a new input, the 'inner' myOnChange exits and then the 'outer' myOnchange exits.
I'm assuming this is because the focus change fires the onchange()?. I know there is some difference in behaviour between browsers in this.
I would like to stop the .focus() (which seems to be the problem) to NOT call the onchange(), so myOnChange() doesn't get called twice. Anybody know how?
There's a way easier and more reasonable solution. As you expect onchange fire when the input value changes, you can simply explicitly check, if it was actually changed.
function onChangeHandler(e){
if(this.value==this.oldvalue)return; //not changed really
this.oldvalue=this.value;
// .... your stuff
}
A quick fix (untested) should be to defer the call to focus() via
setTimeout(function() { ... }, 0);
until after the event handler has terminated.
However, it is possible to make it work without such a hack; jQuery-free example code:
<head>
<style>
input { display: block; }
</style>
<body>
<div></div>
<script>
var div = document.getElementsByTagName('div')[0];
var field = document.createElement('input');
field.type = 'text';
field.onchange = function() {
// only add a new field on change of last field
if(this.num === div.getElementsByTagName('input').length)
div.appendChild(createField(this.num + 1));
this.nextSibling.focus();
};
function createField(num) {
var clone = field.cloneNode(false);
clone.num = num;
clone.onchange = field.onchange;
return clone;
}
div.appendChild(createField(1));
</script>
I can confirm myOnChange gets called twice on Chrome. But the context argument is the initial input field on both calls.
If you remove the alert call it only fires once. If you are using the alert for testing only then try using console instead (although you need to remove it for testing in IE).
EDIT: It seems that the change event fires twice on the enter key. The following adds a condition to check for the existence of the new field.
function myOnChange(context, curNum) {
nextNum = curNum+1;
if ($('#prefix_'+nextNum).length) return false;// added to avoid duplication
$(context.parentNode).append('<input type="text" onchange="return myOnChange(this,'+nextNum+')" id="prefix_'+nextNum+'" >');
$('#prefix_'+nextNum)[0].focus();
return false;
}
Update:
The $('#prefix_'+nextNum).focus(); does not get called because focus is a method of the dom object, not jQuery. Fixed it with $('#prefix_'+nextNum)[0].focus();.
The problem is indeed that because of the focus(), the onchange is called again. I don't know if this is a good sollution, but this adding this to the function is a quick sollution:
context.onchange = "";
(The onchange is called again, but is now empty. This is also good because this function should never be called twice. There will be some interface changes in the final product that help with problems that would arise from this (mistakes and all), but in the end this is something I probably would have done anyway).
sollution here: http://jsfiddle.net/k4WKH/2/
As #johnhunter says, the focus does not work in the example, but it does in my complete code. I haven't looked into what's going on there, but that seems to be a separate problem.
maybe this some help to anybody, for any reason, in chrome when you attach an event onchage to a input text, when you press the enterkey, the function in the event, do it twice, i solve this problem chaged the event for onkeypress and evaluate the codes, if i have an enter then do the function, cause i only wait for an enterkey user's, that not works for tab key.
input_txt.onkeypress=function(evt){
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
if(charCode === 13) evaluate( n_rows );
};
Try this example:
var curNum = 1;
function myOnChange( context )
{
curNum++;
$('<input type="text" onchange="return myOnChange( this )" id="prefix_'+ curNum +'" >').insertAfter( context );
$('#prefix_'+ curNum ).focus();
return false;
}
jsFiddle.
I have the following code to display a textbox in a HTML webpage.
<input type="text" id="userid" name="userid" value="Please enter the user ID" />
When the page displays, the text contains the Please enter the user ID message. However, I found that the user needs to click 3 times in order to select all the text (in this case it is Please enter the user ID).
Is it possible to select the entire text with only one click?
Edit:
Sorry, I forgot to say: I must use the input type="text"
You can use the JavaScript .select() method for HTMLElement:
<label for="userid">User ID</label>
<input onClick="this.select();" value="Please enter the user ID" id="userid" />
But apparently it doesn't work on mobile Safari. In those cases you can use:
<input onClick="this.setSelectionRange(0, this.value.length)" value="Sample Text" id="userid" />
The previously posted solutions have two quirks:
In Chrome the selection via .select() doesn't stick - adding a slight timeout resolves this issue.
It's impossible to place the cursor at a desired point after focus.
Here's a complete solution that selects all text on focus, but allows selecting a specific cursor point after focus.
$(function () {
var focusedElement;
$(document).on('focus', 'input', function () {
if (focusedElement == this) return; //already focused, return so user can now place cursor at specific point in input.
focusedElement = this;
setTimeout(function () { focusedElement.select(); }, 100); //select all text in any field on focus for easy re-entry. Delay sightly to allow focus to "stick" before selecting.
});
});
Html (you'll have to put the onclick attribute on every input you want it to work for on the page)
<input type="text" value="click the input to select" onclick="this.select();"/>
OR A BETTER OPTION
jQuery (this will work for every text input on the page, no need to change your html):
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
<script type="text/javascript">
$(function(){
$(document).on('click','input[type=text]',function(){ this.select(); });
});
</script>
You should not use this approach to provide examples for input values (any more).
The best option is to now use the placeholder HTML attribute if possible:
<label for="userid">User ID</label>
<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />
This will cause the text to show unless a value is entered, eliminating the need to select text or clear inputs.
Beware that placeholders are no replacement for labels, as they disappear once text is entered, and pose issues for accessibility.
You can always use document.execCommand (supported in all major browsers)
document.execCommand("selectall", null, false);
Selects all text in the currently focused element.
Update 2021: execCommand is now deprecated.
It's probably for the best to be honest, as it was an old IE API which had been adopted by the other browsers, and it was always a little weird to work with. Nevertheless, it was nice to have one solution which worked both with <input> fields and contenteditable elements.
.select() is probably the best way to go for <input> fields these days.
For contenteditable, the modern solution there is to use the range API.
Note: When you consider onclick="this.select()", At the first click, All characters will be selected, After that maybe you wanted to edit something in input and click among characters again but it will select all characters again. To fix this problem you should use onfocus instead of onclick.
Try:
onclick="this.select()"
It works great for me.
The answers listed are partial according to me. I have linked below two examples of how to do this in Angular and with JQuery.
This solution has the following features:
Works for all browsers that support JQuery, Safari, Chrome, IE, Firefox, etc.
Works for Phonegap/Cordova: Android and IOs.
Only selects all once after input gets focus until next blur and then focus
Multiple inputs can be used and it does not glitch out.
Angular directive has great re-usage simply add directive select-all-on-click
JQuery can be modified easily
JQuery:
http://plnkr.co/edit/VZ0o2FJQHTmOMfSPRqpH?p=preview
$("input").blur(function() {
if ($(this).attr("data-selected-all")) {
//Remove atribute to allow select all again on focus
$(this).removeAttr("data-selected-all");
}
});
$("input").click(function() {
if (!$(this).attr("data-selected-all")) {
try {
$(this).selectionStart = 0;
$(this).selectionEnd = $(this).value.length + 1;
//add atribute allowing normal selecting post focus
$(this).attr("data-selected-all", true);
} catch (err) {
$(this).select();
//add atribute allowing normal selecting post focus
$(this).attr("data-selected-all", true);
}
}
});
Angular:
http://plnkr.co/edit/llcyAf?p=preview
var app = angular.module('app', []);
//add select-all-on-click to any input to use directive
app.directive('selectAllOnClick', [function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var hasSelectedAll = false;
element.on('click', function($event) {
if (!hasSelectedAll) {
try {
//iOS, Safari, thows exception on Chrome etc
this.selectionStart = 0;
this.selectionEnd = this.value.length + 1;
hasSelectedAll = true;
} catch (err) {
//Non iOS option if not supported, e.g. Chrome
this.select();
hasSelectedAll = true;
}
}
});
//On blur reset hasSelectedAll to allow full select
element.on('blur', function($event) {
hasSelectedAll = false;
});
}
};
}]);
input autofocus, with onfocus event:
<INPUT onfocus="this.select()" TYPE="TEXT" NAME="thing" autofocus>
This lets you open a form with the desired element selected. It works by using autofocus to hit the input, which then sends itself an onfocus event, which in turn selects the text.
I was looking for a CSS-only solution and found this works for iOS browsers (tested safari and chrome).
It does not have the same behavior on desktop chrome, but the pain of selecting is not as great there because you have a lot more options as a user (double-click, ctrl-a, etc):
.select-all-on-touch {
-webkit-user-select: all;
user-select: all;
}
Indeed, use onclick="this.select();" but remember not to combine it with disabled="disabled" - it will not work then and you will need to manually select or multi-click to select, still. If you wish to lock the content value to be selected, combine with the attribute readonly.
You can replace
<input type="text" id="userid" name="userid" value="Please enter the user ID" />
With:
<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />
The placeholder is used to replace value as how you wanted people to be able to Type in the text box without having to click multiple times or using ctrl + a. Placeholder makes it so it isn't a value but as the name suggests a place holder. That is what is used in multiple online forms that says "Username here" or "Email" and when you click on it the "Email" disappears and you can start typing right away.
Here's a reusable version of Shoban's answer:
<input type="text" id="userid" name="userid"
value="Please enter the user ID" onfocus="Clear(this);"
/>
function Clear(elem)
{
elem.value='';
}
That way you can reuse the clear script for multiple elements.
Here's an example in React, but it can be translated to jQuery on vanilla JS if you prefer:
class Num extends React.Component {
click = ev => {
const el = ev.currentTarget;
if(document.activeElement !== el) {
setTimeout(() => {
el.select();
}, 0);
}
}
render() {
return <input type="number" min={0} step={15} onMouseDown={this.click} {...this.props} />
}
}
The trick here is to use onMouseDown because the element has already received focus by the time the "click" event fires (and thus the activeElement check will fail).
The activeElement check is necessary so that they user can position their cursor where they want without constantly re-selecting the entire input.
The timeout is necessary because otherwise the text will be selected and then instantly unselected, as I guess the browser does the cursor-positioning check afterwords.
And lastly, the el = ev.currentTarget is necessary in React because React re-uses event objects and you'll lose the synthetic event by the time the setTimeout fires.
I think its better to control via event. This variant looks pretty intuitively and work with ts as well:
onFocus={e => {
e.target.select();
}
If you need selectAll every click then you can use this:
onClick={e => {
e.target.focus();
e.target.select();
}
The exact solution to what you asked is :
<input type="text" id="userid" name="userid" value="Please enter the user ID" onClick="this.setSelectionRange(0, this.value.length)"/>
But I suppose,you are trying to show "Please enter the user ID" as a placeholder or hint in the input.
So,you can use the following as a more efficient solution:
<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />
The problem with catching the click event is that each subsequent click within the text will select it again, whereas the user was probably expecting to reposition the cursor.
What worked for me was declaring a variable, selectSearchTextOnClick, and setting it to true by default. The click handler checks that the variable's still true: if it is, it sets it to false and performs the select(). I then have a blur event handler which sets it back to true.
Results so far seem like the behavior I'd expect.
(Edit: I neglected to say that I'd tried catching the focus event as someone suggested,but that doesn't work: after the focus event fires, the click event can fire, immediately deselecting the text).
This question has options for when .select() is not working on mobile platforms: Programmatically selecting text in an input field on iOS devices (mobile Safari)
Html like this
<input type="text" value="click the input to select" onclick="javascript:textSelector(this)"/>
and javascript code without bind
function textSelector(ele){
$(ele).select();
}
Well this is normal activity for a TextBox.
Click 1 - Set focus
Click 2/3 (double click) - Select text
You could set focus on the TextBox when the page first loads to reduce the "select" to a single double-click event.
Use "placeholder" instead of "value" in your input field.
Use this:
var textInput = document.querySelector("input");
textInput.onclick = function() {
textInput.selectionStart = 0;
textInput.selectionEnd = textInput.value.length;
}
<input type="text">
I'm using the focus-attribute in my vue application
<input #focus="$event.target.select()" />
If you are using AngularJS, you can use a custom directive for easy access:
define(['angular'], function () {
angular.module("selectionHelper", [])
.directive('selectOnClick', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.on('click', function () {
this.select();
});
}
};
});
});
Now one can just use it like this:
<input type="text" select-on-click ... />
The sample is with requirejs - so the first and the last line can be skipped if using something else.
If anyone want to do this on page load w/ jQuery (sweet for search fields) here is my solution
jQuery.fn.focusAndSelect = function() {
return this.each(function() {
$(this).focus();
if (this.setSelectionRange) {
var len = $(this).val().length * 2;
this.setSelectionRange(0, len);
} else {
$(this).val($(this).val());
}
this.scrollTop = 999999;
});
};
(function ($) {
$('#input').focusAndSelect();
})(jQuery);
Based on this post . Thanks to CSS-Tricks.com
If you are just trying to have placeholder text that gets replaced when a user selects the element then it is obviously best practice to use placeholder attribute nowadays. However, if you want to select all of the current value when a field gains focus then a combination of #Cory House and #Toastrackenigma answers seems to be most canonical. Use focus and focusout events, with handlers that set/release the current focus element, and select all when focused. An angular2/typescript example is as follows (but would be trivial to convert to vanilla js):
Template:
<input type="text" (focus)="focus()" (focusout)="focusout()" ... >
Component:
private focused = false;
public focusout = (): void => {
this.focused = false;
};
public focus = (): void => {
if(this.focused) return;
this.focused = true;
// Timeout for cross browser compatibility (Chrome)
setTimeout(() => { document.execCommand('selectall', null, false); });
};
If you are looking for a pure vanilla javascript method, you can also use:
document.createRange().selectNodeContents( element );
This will select all the text and is supported by all major browsers.
To trigger the selection on focus, you just need to add the event listener like so:
document.querySelector( element ).addEventListener( 'focusin', function () {
document.createRange().selectNodeContents( this );
} );
If you want to place it inline in your HTML, then you can do this:
<input type="text" name="myElement" onFocus="document.createRange().selectNodeContents(this)'" value="Some text to select" />
This is just another option. There appears to be a few ways of doing this. (document.execCommand("selectall") as mentioned here as well)
document.querySelector('#myElement1').addEventListener('focusin', function() {
document.createRange().selectNodeContents(this);
});
<p>Cicking inside field will not trigger the selection, but tabbing into the fields will.</p>
<label for="">JS File Example<label><br>
<input id="myElement1" value="This is some text" /><br>
<br>
<label for="">Inline example</label><br>
<input id="myElement2" value="This also is some text" onfocus="document.createRange().selectNodeContents( this );" />
Using placeholder="Please enter the user ID" instead of value="Please enter the user ID" is the best approach for this scenario, but the function can be useful in some cases.
<input> elements can already listen to focus event. We can just add the event listener to it instead of document, and there is no further needs to listen to click.
Plain JavaScript:
document.getElementById("userid").addEventListener("focus", function() {
this.select();
});
With JQuery:
$("#userid").on("focus", function() {
this.select();
});
You may use this.setSelectionRange(0, this.value.length) instead of this.select() depends on your purpose but that will not work on some input types such as number.
Live demo
<input id="my_input" style="width: 400px; height: 30px;" value="some text to select">
<br>
<button id="select-bn" style="width: 100px; height: 30px; margin-top: 20px;cursor:pointer;">Select all</button>
<br><br>
OR
<br><br>
Click to copy
<br><br>
<input id="my_input_copy" style="width: 400px; height: 30px;" value="some text to select and copy">
<br>
<button id="select-bn-copy" style="width: 170px; height: 30px; margin-top: 20px;cursor:pointer;">Click copy text</button>
<script type="text/javascript">
$(document).on('click', '#select-bn', function() {
$("#my_input").select();
});
//click to select and copy to clipboard
var text_copy_bn = document.getElementById("select-bn-copy");
text_copy_bn.addEventListener('click', function(event) {
var copy_text = document.getElementById("my_input_copy");
copy_text.focus();
copy_text.select();
try {
var works = document.execCommand('copy');
var msg = works ? 'Text copied!' : 'Could not copy!';
alert(msg);
} catch (err) {
alert('Sorry, could not copy');
}
});
</script>
I've got a fairly standard username/password entry box on a web site I'm building. The password box has a div containing "Password" overlaid on top of it, which is set to display: none; on focus or click.
This works great until the user asks their browser to remember the password: in that case you can end up with the situation in the attached screen shot.
My question then is: is there an event that I can bind to that will trigger when the password field autofills so I can hide the help div?
Here's the crappy solution I came up:
I added an interval timer to the site that checks the value of the box, and hides the help text when the value is not an empty string.
Why don't you verify if the password textbox is filled on the document.ready event and on each usernametextfield.onchange event? That way you don't need a timer and it should be right.
Note: It could be (I haven't tested this) that the onchange event will be triggered before the browser has filled in the password field. To handle that short timespan, you could launch the check a few 100 milliseconds later using setTimeOut.
I used the blur event on the username to check if the pwd field had been auto-filled.
$('#userNameTextBox').blur(function () {
if ($('#userNameTextBox').val() == "") {
$('#userNameTextBox').val("User Name");
}
if ($('#passwordTextBox').val() != "") {
$('#passwordTextBoxClear').hide(); // textbox with "Password" text in it
$('#passwordTextBox').show();
}
});
This works for IE, and should work for all other browsers (I've only checked IE)
maybe my solution with jquery will catch your attention :).
here is what i did for solution:
$('form input').bind('change', function(){
$('form').find('input').each(function(){
label = $(this).prev('label');
if($(this).val()!==''){
label.addClass('active');
}
});
});
first of all i bind change event with input field so when one of the input fields get changed i do the next step which is testing all input fields and any of them has changed value i make then what i want with it
for more clarification => JSFIDDLE
For chrome :-webkit-autofill class works perfectly.
For a browser independent solution I what found was, the mouseleave event is fired whenever mouse is hovered over the browser's autofill dropdown. You can write handler on the input or its parent elements or event window. see the code below.
In HTML:
<div id="banner-message">
<div>
<input type="text" id="name" name="name" placeholder="name"/>
</div>
<div>
<input type="text" id="email" name="email" placeholder="email"/>
</div>
<div>
<input type="password" name="password" placeholder="password"/>
</div>
</div>
<div id="event-log"> </div>
In jQuery:
var banner = $("#banner-message")
var eventlog = $("#event-log");
var inputs = $("input");
//Following event fired when hovered over autofill dropdown,
banner.on("mouseleave", function(event) {
var targetid = event.target.id;
eventlog.html('Source id::'+targetid);
});
In the above code when the event is fired, event.target is the element from which the pointer is left and entered into dropdown.
one thing to note here is, you have to identify the correct way to detect mouseleave which is fired only when autofilled.The above solution worked for me.
see this fiddle: https://jsfiddle.net/nilesh_ramteke/nt7a1ruw/20/
Please configure your browser for autofill before trying above solution.