查找输入元素的“类型”

我希望能够找到类型的东西在页面上使用 JavaScript。 问题如下: 我需要检查某个特定区域是复选框/单选按钮/还是文本字段。

如果它是一个复选框或单选按钮,它没有长度(没有字符串) ,否则如果它是一个文本字段,我需要检查它是否包含字符。页面是动态创建的,因此有时会显示复选框,有时会显示文本字段。

所以我的想法是找到输入的类型,然后决定做什么。

如有任何建议将不胜感激。

163195 次浏览

检查 type属性,这样够了吗?

如果要检查表单中的输入类型,请使用以下代码:

<script>
function getFind(obj) {
for (i = 0; i < obj.childNodes.length; i++) {
if (obj.childNodes[i].tagName == "INPUT") {
if (obj.childNodes[i].type == "text") {
alert("this is Text Box.")
}
else if (obj.childNodes[i].type == "checkbox") {
alert("this is CheckBox.")
}
else if (obj.childNodes[i].type == "radio") {
alert("this is Radio.")
}
}
if (obj.childNodes[i].tagName == "SELECT") {
alert("this is Select")
}
}
}
</script>


<script>
getFind(document.myform);
</script>

如果您正在使用 jQuery,您可以轻松地检查任何元素的类型。

    function(elementID){
var type = $(elementId).attr('type');
if(type == "text") //inputBox
console.log("input text" + $(elementId).val().size());
}

同样,你也可以检查其他类型并采取适当的措施。

检查输入类型

<!DOCTYPE html>
<html>
<body>


<input type=number id="txtinp">
<button onclick=checktype()>Try it</button>


<script>
function checktype()
{
alert(document.getElementById("txtinp").type);
}
</script>


</body>
</html>