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" id="Vendor_hotel" />
<label>Car Vendor Codes</label>
<input type="text" 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")) {
CodePudding user response:
It's been a while since I don't work with jQuery, but I'll do:
const vendors = $('.vendor-autocomplete')
for (const vendor of vendors) {
switch (vendor.attr('data-vendor')) {
case 'hotel':
//do stuff
break
case 'car':
// do some other stuff
break
default:
// just in case
break
}
}
<label>Hotel Vendor Codes</label>
<input type="text" data-vendor="hotel" />
<label>Car Vendor Codes</label>
<input type="text" data-vendor="car" />
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 custom data
attr.
CodePudding user response:
Looks like this works: Reference: api.jquery.com/focus-selector
if (vendorCar.is(":focus"))
console.log("Input is Car Vendors");
CodePudding user response:
The issue is $(this)
is undefined.
But using an .each()
loop would provide you the element
that you need.
var vendorAutocompletes = $('.vendor-autocomplete');
var vendorCar = $('.vendor-car');
if (vendorAutocompletes.length > 0) {
vendorAutocompletes.each(function(index, element) {
$(element).autocomplete({
source: function (request, response) {
if ($(element).attr("id") == vendorCar.attr("id")) {
console.log('This input is Car Vendors');
return getVendors(request.term, VendorTypes.Car, response);
} else {
console.log('This input is Hotel Vendors');
return getVendors(request.term, VendorTypes.Hotel, response);
}
}
});
})
}
I added the possibly missing return
...