将值添加到活动输入字段

时间:2015-07-17 17:09:44

标签: javascript jquery html selecteditem

如何在所有input字段中为活动输入字段添加值?

我使用autofocus属性来获取" the_field" ,它没有任何回报。

1 个答案:

答案 0 :(得分:2)

香草JS

首先提供您可能想要将内容添加到某个类的所有输入,然后将其称为input-field。如果您使用的是vanilla JS,您可以像这样执行JS:

//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';
}

其中hasClass是一个检查元素是否具有特定类(从here被盗)的函数:

hasClass(el, cls) {
    if (!el.className) {
        return false;
    } else {
        var newElementClass = ' ' + el.className + ' ';
        var newClassName = ' ' + cls + ' ';
        return newElementClass.indexOf(newClassName) !== -1;
    }
}

或者(正如Edwin Reynoso所指出的),如果您的代码在10以下的IE中不受支持,则可以使用classList.contains()

if(focused.classList.contains('input-field')) {
    ...

如果您不想添加额外的类,只是检查它是否是带有类型文本的输入,您可以检查这样的内容:

if(focused.tagName == 'input' && focued.getAttribute('type') == 'text') {
    ...

的jQuery

或者,如果您更喜欢使用JQuery,则无需额外功能即可实现:

focused = jQuery(':focus');

if(focused.hasClass('input-field')) {
    focused.val(focused.val() + '3');
}

同样,如果你想跳过课程并检查输入类型文本,请使用:

if(focused.is('input[type=text]')) {
    ...

另请参阅此问题:"How to get the focused element with jQuery?"

相关问题