I have multiple input elements that are very similar in look and feel. The only difference is each input will have a different type of input code (Hotel vendor codes or Car vendor codes). Instead of duplicating autocomplete JavaScript code, I would like to re-use the same code for each input element but I need a way to identify which input is currently in focus so that the return values are the correct codes. Below is the the basic concept. How would I structure the if condition to know if my current input in focus is "vendor-car" or "vendor-hotel"?
HTML:
<label>Hotel Vendor Codes</label>
<input type="text" class="form-control vendor-autocomplete vendor-hotel" id="Vendor_hotel" />
<label>Car Vendor Codes</label>
<input type="text" class="form-control vendor-autocomplete vendor-car" id="Vendor_car" />
TypeScript:
var vendorAutocompletes = $('.vendor-autocomplete');
var vendorCar = $('.vendor-car');
if (vendorAutocompletes.length > 0) {
vendorAutocompletes
.autocomplete({
source: function (request, response) {
if ($(this).attr("id") == vendorCar.attr("id")) {
console.log('This input is Car Vendors');
getVendors(request.term, VendorTypes.Car, response);
} else {
console.log('This input is Hotel Vendors');
getVendors(request.term, VendorTypes.Hotel, response);
}
}
});
}
Trying to determine if the event associated with the current input DOM element is of type "vendor-car" or "vendor-hotel". Instead of the current element, $(this).attr("id")
is undefined.
if ($(this).attr("id") == vendorCar.attr("id")) {
3
Answers
Looks like this works: Reference: api.jquery.com/focus-selector
It’s been a while since I don’t work with jQuery, but I’ll do:
If this is your only use case, I don’t think you require the
id
attr for that. Just use the same class for all the inputs and store the vendor type in a customdata
attr.The issue is
$(this)
is undefined.But using an
.each()
loop would provide you theelement
that you need.I added the possibly missing
return
…