Roland
Roland

Reputation: 9701

Get the ID of a form?

I'm using the following code to attach an event to the submit button of a form :

$('form.manage-users-form').on('click','button.special',function() {

    if ($(this).hasClass('selected')){
        console.log('This user is already special');
    } else {

        $(this).parent().find('button').removeClass('selected');
        $(this).addClass('selected');

        var user_id = $(this).closest("form[id]").val();

        console.log('This user is now special');
        console.log(user_id);
    }
    return false;
});

And you can see that I'm also trying to get the id of the form, but when I check the console I get (an empty string). Why is that and how can I properly get the ID of the form ?

Upvotes: 15

Views: 72299

Answers (4)

Milan
Milan

Reputation: 3013

Try this instead. Assuming there is a Single Form on the Page.

 var formid = $('form').attr('id');

Will help you out.

Upvotes: 8

vdeantoni
vdeantoni

Reputation: 1968

Have you tried?

var user_id = $(this).closest("form").attr('id');

The id of the element is an attribute, you can extract any attribute (including the id) using .attr().

.val() is used to extract the value of the element, which makes no sense in a form.

More Info:

.val()
.attr()

Upvotes: 37

Bogdan Emil Mariesan
Bogdan Emil Mariesan

Reputation: 5647

Try the following:

  var user_id = $(this).closest("form").attr("id");

Will be back with an edit as soon as i test this.

Upvotes: 1

Didier Ghys
Didier Ghys

Reputation: 30666

.val() is used to get value of form elements, not attribute.

Use .attr():

var user_id = $(this).closest("form[id]").attr('id');

You can also extract the DOMElement and use pure javascript to get the ID:

var user_id = $(this).closest("form[id]")[0].id;

Upvotes: 6

Related Questions