检查输入的类型是否为“文本/号码/电子邮件/等"? [英] Check if input is of type "text/number/email/etc"?

查看:102
本文介绍了检查输入的类型是否为“文本/号码/电子邮件/等"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Javascript(不是jQuery)检查给定的输入元素是否可由用户使用键盘写出.

I need to check with Javascript (not jQuery) if the given input element is writable by the user using the keyboard.

我想排除复选框,单选框,按钮,重置,提交,图像等.

I'd like to exclude checkboxes, radios, buttons, resets, submits, image and so on.

有没有一种简单的方法可以不列出所有输入类型?

Is there a simple way to do it without list all the input types?

这是我当前的代码:

if (element.getAttribute === undefined) {
    return false;
}

var eTag  = element.tagName;
var eType = element.getAttribute('type');
var isTextInput = (eTag === 'INPUT' || eTag === 'TEXTAREA') && ( eType !== null || eType === 'text' || eType === 'password');
var isEnabledInput = element.disabled === false && element.readOnly === false;
var isContentEditable = ( element.contentEditable && element.contentEditable === true );

// stop for enabled text inputs, selects and contentEditable areas
return (isTextInput && isEnabledInput) || eType === 'SELECT' || isContentEditable;

从逻辑上讲,&& ( eType !== null || eType === 'text' || eType === 'password');不足以全部检查它们.

Logically the && ( eType !== null || eType === 'text' || eType === 'password'); is not enough to check them all.

推荐答案

将其发布为答案是因为可以解决问题,但严格意义上并不是我要的.

Posting this as an answer because fixes the problem, but it's not strictly what I'm asking for.

我还在等待更清洁的解决方案.

I'm still waiting for a cleaner solution.

var notTextual = [
    'button',
    'checkbox',
    'hidden',
    'image',
    'radio',
    'reset',
    'submit'
];

if (element.getAttribute === undefined) {
    return false;
}

var eTag  = element.tagName;
var eType = element.getAttribute('type');
var isTextInput = (eTag === 'INPUT' || eTag === 'TEXTAREA') && !notTextual.contains(eType);
var isEnabledInput = element.disabled === false && element.readOnly === false;
var isContentEditable = ( element.contentEditable && element.contentEditable === true );

// stop for enabled text inputs, selects and contentEditable areas
return (isTextInput && isEnabledInput) || eType === 'SELECT' || isContentEditable;

这篇关于检查输入的类型是否为“文本/号码/电子邮件/等"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆