Barry Tormey
Barry Tormey

Reputation: 3146

Get ID by Element Class

I have several text boxes which have drop downs on them. When a user clicks on the field with the drop down class, I want to get the ID of that field. This seems like it should be simple, but I can't quite seem to figure it out...

I have tried:

$(".dropdown").click(function () {
    alert(this.getElementById);
});

Yet this only returns undefined.

Upvotes: 1

Views: 192

Answers (5)

Jijo John
Jijo John

Reputation: 1375

Its simple you can alert the element id with the below code written by me

          $(".dropdown").click(function() {

          var id = $('.dropdown').attr('id');
          alert(id);

         });

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 122026

Wrong syntax.You have to write

$(".dropdown").click(function () {
    alert(this.id);
});

Correct Syntax:

var idStr = element.id; // Get the id.
element.id = idStr; // Set the id

Upvotes: 3

EnterSB
EnterSB

Reputation: 1162

If I understood well, you want this:

$(".dropdown").click(function () {
    alert($(this).attr('id'));
});

correct me if I am wrong

Upvotes: 0

Claudio Redi
Claudio Redi

Reputation: 68440

You're using getElementById incorrectly. It's a function used to get a dom element on your page using an id as filter condition. It's not used to get element id.

Correct usage of getElementById is

var elem = document.getElementById('theid');

You simply have to use

alert(this.id);

Upvotes: 1

A. Wolff
A. Wolff

Reputation: 74410

ID is a property of the object, so just use following code:

$(".dropdown").click(function () {
    alert(this.id);
});

Upvotes: 7

Related Questions