jQuery find input type (but also for select)

旧城冷巷雨未停 提交于 2019-12-20 10:34:16

问题


I need to find the input type for radio buttons, text, and selects. Its easy to find the input type of anything with <input type="x"> since $(this).attr("type") would return x

My issue is that I need to support <select> elements, which dont have the type attribute. The end goal is to do return either radio, text, or select.

I thought of doing something like this, but I was curious if there's a better way:

if ($(this).tagName == "input") {
    var result = $(this).attr("type");   //returns radio or text (the attr type)
} else {
    var result = $(this).tagName;        //returns select (the element type)
}

Thanks all!


回答1:


You can do this (fiddle here), make some sort of easy to use plugin:

$.fn.getType = function(){ return this[0].tagName == "INPUT" ? this[0].type.toLowerCase() : this[0].tagName.toLowerCase(); }

And use it like this

$(".element").getType(); // Will return radio, text, checkbox, select, textarea, etc (also DIV, SPAN, all element types)
$(".elList").getType(); // Gets the first element's type

Which will get the type of the first element which is selected.

Other info

If you just want to have some selectors you can use this:

$("input:text, input:radio, select");

Or select all form controls (more info):

$(":input") // can return all form types



回答2:


All types of input box and select box getting together by jQuery find :

$('#myForm').find('select,input').each(function(i,box){
     alert($(box).attr('name'));
}


来源:https://stackoverflow.com/questions/9116694/jquery-find-input-type-but-also-for-select

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!