Get the ID of a form?
Asked Answered
D

4

15

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 ?

Defensible answered 13/3, 2012 at 13:42 Comment(0)
A
37

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()

Accompany answered 13/3, 2012 at 13:44 Comment(1)
With newer versions of jQuery, you usually want .prop() instead of .attr(). Regardless, you do not need jQuery to retrieve an element's ID. #4652423Leonardoleoncavallo
F
8

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

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

Will help you out.

Feuar answered 7/7, 2014 at 7:28 Comment(1)
Assuming there aren't multiple forms on the pageEdik
L
6

.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;
Lantha answered 13/3, 2012 at 13:44 Comment(0)
L
1

Try the following:

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

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

Lindholm answered 13/3, 2012 at 13:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.