9

I am trying to use JQuery to get the type of control and following is the code that I am using.

$('#selCity').attr('type')

where selCity is of type select. When I try the above code it returns as undefined but when I use the alternative code with Javascript, it returns the correct type.

Please look into this fiddle to understand it clearly: http://jsfiddle.net/Ye8e9/

Could someone advice on how I can acheive this correctly using JQuery? Is this an issue with JQuery or am I making a mistake?

4 Answers 4

10

Use

$('#selCity').prop('type')

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.

Reference

DEMO

Sign up to request clarification or add additional context in comments.

2 Comments

@AbishekRSrikaanth check my reference
@AbishekRSrikaanth you can use .prop for all type html elements, check my demo
8

if you mean the type of tag, the use this

 $("#selCity").get(0).tagName

See your demo here

1 Comment

Rab Nawaz, Is there a generic approach that I can follow to get for all the controls. If I try the above code for a textbox, I get the value "INPUT" and with this output am not sure if the control is a hidden field or a textbox or a password field.
0

Use nodeName to get 'type of Tag'. '.type' refers to attribute 'type' which select doesn't have.

document.getElementById('selCity').nodeName

1 Comment

Am not sure or dont understand by what you mean by attribute 'type' does not exist for select control. How does javascript output data when the following code is executed document.getElementById('selCity').type
0

you are getting undefined because there is not type attribute in select.

try this one

$('#selCity')[0].tagName;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.