Javascript 查找输入元素的“类型”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/3510867/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Finding the 'type' of an input element
提问by Julio
I'd like to be able to find the type of something on the page using javascript. The problem is as follows: I need to check whether a specific area is a checkbox/radio button/ or text field.
我希望能够使用 javascript 在页面上找到某些内容的类型。问题如下:我需要检查特定区域是否是复选框/单选按钮/或文本字段。
If its a checkbox or radio button it doesnt have a length(no strings in it) otherwise if its a textfield I need to check whether or not it contains characters. The page is created dynamically so sometimes a checkbox may be displayed other times a text field.
如果它是一个复选框或单选按钮,它没有长度(其中没有字符串),否则如果它是一个文本字段,我需要检查它是否包含字符。该页面是动态创建的,因此有时可能会显示一个复选框,有时可能会显示一个文本字段。
So my thinking is find the type of input, then determine what to do.
所以我的想法是找到输入的类型,然后确定要做什么。
Any suggestions would be appreciated.
任何建议,将不胜感激。
Thanks in advance.
提前致谢。
回答by troelskn
Check the typeproperty. Would that suffice?
检查type财产。这样就够了吗?
回答by PPShein
If you want to check the type of input within form, use the following code:
如果要检查表单中输入的类型,请使用以下代码:
<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.")
            }
            if (obj.childNodes[i].type == "checkbox") {
                alert("this is CheckBox.")
            }
            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>
回答by kapser
If you are using jQuery you can easily check the type of any element.
如果您使用 jQuery,您可以轻松检查任何元素的类型。
    function(elementID){    
    var type = $(elementId).attr('type');
    if(type == "text") //inputBox
     console.log("input text" + $(elementId).val().size());
   }
similarly you can check the other types and take appropriate action.
同样,您可以检查其他类型并采取适当的措施。

