How can I add value to the active input field among all the input
fields?
I used autofocus
attribute to get "the_field" , it didn't return anything.
How can I add value to the active input field among all the input
fields?
I used autofocus
attribute to get "the_field" , it didn't return anything.
First give all the inputs you might want to add stuff to a certain class, lets call it input-field
. If you are using vanilla JS you can do the JS like this:
//Get the focused element.
var focused = document.activeElement;
//Check that it is one of the elements you want to add stuff to.
if(hasClass(focused, 'input-field')) {
//Add whatever you want to add, lets say a number "3".
focused.value = focused.value + '3';
}
Where hasClass
is a function that checks if an element has a particular class (stolen from here):
hasClass(el, cls) {
if (!el.className) {
return false;
} else {
var newElementClass = ' ' + el.className + ' ';
var newClassName = ' ' + cls + ' ';
return newElementClass.indexOf(newClassName) !== -1;
}
}
Alternatively (as pointed out by Edwin Reynoso), if you are fine with your code not being supported in IE below version 10, you can use classList.contains()
:
if(focused.classList.contains('input-field')) {
...
If you dont want to add the extra class and just check if it is a input with type text you can check for that like this instead:
if(focused.tagName == 'input' && focued.getAttribute('type') == 'text') {
...
Or if you prefer working with JQuery you can do it without an extra function:
focused = jQuery(':focus');
if(focused.hasClass('input-field')) {
focused.val(focused.val() + '3');
}
Again, if you want to skip the class and check for an input type text just use this:
if(focused.is('input[type=text]')) {
...
Also see this question: "How to get the focused element with jQuery?"