Reputation: 84
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="selectajax".
I want to get the select's id="xxx" or name="xyz" 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>
$(document).ready(function() {
$('.selectajax').select2({
var name1 = $(this).attr("name");
alert(name1);
ajax: {
url: 'ajax-products.php',
data: function(params) {
var query = {
search: params.term,
type: 'public'
}
// Query parameters will be ?search=[term]&type=public
return query;
}
}
});
});
</script>
Any help is appreciated.
Thanks in advance.
Upvotes: -1
Views: 145
Reputation: 2540
I know it is very late to answer, but I was stuck on the same issue.
I added the data-attribute-id
to the input name
<select ... data-attribute-id='<?= $attributeId?>'>...</select>
Then I initialized the select2 and send the attribute id in the parameter of the data.
$('#option').select2({
...
ajax: {
url: '#',
dataType: 'json',
type: 'GET',
delay: 250,
data: function(params) {
let attribute_id = $(this).attr('data-attribute-id'); // retrieved the id
return {
search: params,
fk_attribute_id: attribute_id, //send here
};
},
processResults: function(data, params) {
return {
results: $.map(data.attributeValues, function(item) {
return {
text: item.attribute_value,
id: item.id,
}
})
};
},
});
Hope it helps for anyone in the near future.
Upvotes: -1