ilyo
ilyo

Reputation: 36411

jQuery backward selection

I have a form and i'm using this to select it's radio buttons:

$('form[id^="form-"]').find("input:radio");

But when I use a function on it I have to use this (so that i'll know from which form the function is fired) and this gives me form > radio-button. How can I use this to get the ID of the form?

Upvotes: 0

Views: 736

Answers (4)

morgar
morgar

Reputation: 2407

$(this).parent().attr('id');

parents() is because I don't know if the inputs are direct descendants of form.

Upvotes: 0

Andy E
Andy E

Reputation: 344585

The simplest and most efficient way is to access the form property of the element in question:

alert(this.form.id);

Upvotes: 3

Naftali
Naftali

Reputation: 146310

If this is a child element just do:

var form_id = $(this).parent().get(0).id;
//or
var form_id = $(this).parent().attr('id');

Upvotes: 0

Fenton
Fenton

Reputation: 250972

To traverse from the input to its containing form and get the id, you would use:

$(this).closest('form[id^="form-"]').attr("id");

http://api.jquery.com/category/traversing/

Upvotes: 2

Related Questions