hd.
hd.

Reputation: 18306

Get type of form element with jQuery

I have a form with some inputs and selects. I want to get the type of element on its click with jQuery. I know I can use attr("input") to get if the element is radio, checkbox or text but what about selects and textarea?

Is there a overall function like .type() to get it?

Upvotes: 13

Views: 28548

Answers (5)

gdoron
gdoron

Reputation: 150263

First .attr('input') won't give you the type, use this for inputs:

var type = $('input').attr('type')

For inputs, select and textarea:

$('#formId :input').click(function() {
    alert(this.tagName != 'INPUT' ? this.tagName : this.type);
});​

:input selector docs:

Description: Selects all input, textarea, select and button elements.

JSFiddle DEMO

Upvotes: 6

adeneo
adeneo

Reputation: 318222

Getting the element type (input, select, div, span etc):

var elementType = $(this).prop('tagName');

Checking for specific element type:

var is_element_input = $(this).is("input"); //true or false

Getting the input type (input type="button" etc)

var inputType = $(this).attr('type');

Upvotes: 3

alex
alex

Reputation: 490283

You can use :input to select all input elements.

You could try something such as...

$('#your-form').find(':input').click(function() {
    var type = this.type || this.tagName.toLowerCase();
    alert(type);
});

For input elements, this should give you their type attribute, such as text, radio, checkbox, etc.

For select and textarea elements, it should give you the tag name such as select or textarea.

Upvotes: 22

Rasmus
Rasmus

Reputation: 8486

Give all your elements a classname say "checktype" and then use:-

$(".checktype").click(function(){
  alert(this.tagName);
})

Upvotes: 0

elclanrs
elclanrs

Reputation: 94101

Selects and textareas are different tags. Use tagName.

element.tagName

Upvotes: 0

Related Questions