find input type from name
Is there any way to get the type of the input from the name? For instance: for <input type="text" name="abc" />
I want to know whether it is input, textarea or select. So, is it possible to find the type of inpu开发者_开发知识库t from name?
var eltype = $('*[name="abc"]').prop('tagName');
example: http://jsfiddle.net/UDcYD/
EDIT
as @Wesley Murch stated the tagName
property returns a uppercase string, if you need it lower case just do something like that:
var eltype = $('[name="abc"]').prop('tagName').toLowerCase();
@Wesley Murch is right again saying that *
in not neccessary infact [name="abc"]
is enough to select element with name abc
EDIT2
tagName
is a property of the jQuery object you selected with [name="abc"]
which represents its tag name. In your question you called it type but actually the right name is tag name.
EDIT3
If you are using a jQuery version < 1.6 you have to use attr
instead of prop
as prop function has been introduced with jQuery 1.6
var eltype = $('[name="abc"]').attr('tagName').toLowerCase();
anyway my advise is to upgrade jQuery if you do no have too much code relying on the old jQuery you have
For retrieving input type:
$('*[name="abc"]').attr('type');
For retrieving tag name:
$('*[name="abc"] :eq(0)').tagName;
You could use something like this:
$element = $('*[name="target"]');
$result = $('#result');
if ($element.prop('tagName') == 'INPUT') {
$result.text($element.attr('type'));
}
else {
console.log('foo');
$result.text($element.prop('tagName').toLowerCase());
}
This should work for both inputs and <select>
s etc.
Working Example
精彩评论