Title: How to get name or id of the input?
Tags: jquery;jquery-select2
Question: I have few  fields which have different id's and name's. I have specified a common class name to those fields for eg. class=&quot;selectajax&quot;.
I want to get the select's id=&quot;xxx&quot; or name=&quot;xyz&quot; value whenever it gets focus via jquery and I want to do this because i'm using select2 and whenever something is typed for searching via ajax, I want to get the name of the field so I can pass it to the ajax request.
So far I have this code but its producing error:
<script&gt;
$(document).ready(function() {
$('.selectajax').select2({
var name1 = $(this).attr(&quot;name&quot;);
alert(name1);
ajax: {
url: 'ajax-products.php',
data: function(params) {
var query = {
search: params.term,
type: 'public'
}
// Query parameters will be ?search=[term]&amp;type=public
return query;
}
}
});
</script&gt;
Any help is appreciated.
Thanks in advance.
Comment: Why do you need the name or id ? What do you want to achieve by getting that when an element gets focused ?

Comment: I will then send that id or name in the ajax request to get the relevant data and populate the select2 dropdown.



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 0, 'CommentCount': 2, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2021:00:05/31/21', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<jquery><jquery-select2>', 'Title': 'How to get name or id of the input?', 'ViewCount': 51, 'id': 67772043, 'user_AboutMe': '', 'user_AccountId': 14969129.0, 'user_DisplayName': 'Noob Coder', 'user_Reputation': 58.0, 'user_Views': 28.0, 'user_id': 10806531.0}}