jQuery autocomplete on class, how to get id
12,671
Solution 1
Try:
$(this.element).prop("id");
or:
this.element[0].id;
Inside of the source
callback, this
refers to the widget instance. In order to get the element the widget is attached to, you should use this.element
, which is a jQuery object.
Solution 2
I tried it out in a project of mine. This worked for me:
$(this.element.get(0)).attr('id');
Solution 3
I was in a situation similar to you, user1572796
and this is what worked for me:
$(this).prop("id");
Author by
user1572796
I am a web designer, developer, UI engineer and motorcycle enthusiast living in Los Angeles, CA.
Updated on June 04, 2022Comments
-
user1572796 almost 2 years
I have been working on this a while and can't seem to get anywhere. Basically I have the autocomplete on a bunch of inputs by class, but I need to get the specific inputs id to build the object to post the ajax (I have to use POST for this project not GET).
$(".input_autocomplete").autocomplete({ source: function( request, response ) { // here is where I get the hash from local storage, // reference the id and build the object // tried this.id, $(this).prop('id'), no luck $.ajax({ url: '/somepath/filename.htm', contentType: 'application/json', dataType: 'json', type: 'POST', data: JSON.stringify(obj), success: function(json) { return { label: item.label, value: item.label } }, error: function() { // error handling } }); // ajax } // source });
-
rafaelbiten over 11 yearsAndrew, does it have anything to do with the .get(0) that some people use? If yes, this is something that I can't really understand. Why is it necessary to point to the element like that? =\
-
Andrew Whitaker over 11 years@7th: Please see my update.
this
inside of the autocomplete is the widget instance, sothis.element
is the element it was applied to.element.get(0)
will get the first element of a jQuery object and is equivalent toelement[0]
above. -
rafaelbiten over 11 yearsWell, it makes a lot of sense in this scenario, but sometimes I see people using .get(0) that I would never imagine it should be used. Unfortunately I can't think of a good example now. I'll try to pay better attention when I see that again and see if I can understand why it's been used. Thanks for taking the time to explain it to me. It was kind of your part.
-
Andrew Whitaker almost 8 yearsYeah, really you should just need
this.element.prop('id')
. I think the call to jQuery is redundant here. -
Arvind Krmar about 3 yearsthis one; this.element[0].id; worked for me
-
ArabianMaiden about 3 years$(this).prop("id"); worked for me, the others kept providing "undefined"