Sadiksha Gautam
Sadiksha Gautam

Reputation: 5152

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 input from name?

Upvotes: 2

Views: 4198

Answers (3)

Dalen
Dalen

Reputation: 8996

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

Upvotes: 4

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174957

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

Upvotes: 0

J0HN
J0HN

Reputation: 26921

For retrieving input type:

$('*[name="abc"]').attr('type');

For retrieving tag name:

$('*[name="abc"] :eq(0)').tagName;

Upvotes: 0

Related Questions