I am trying to enable an old function made for desktop for mobile touch devices. Everything looks fine now, except the select part. The function will recognize the return key (13) and fill out a form field with the selected option.
It looks like all there is left to do, is to change this part:
else if (e.keyCode == 13) {
I was thinking about something like this, but it does not work:
$('#search-autocomplete li').click(function(e) {
console.log('worked');
});
How can this be altered, so it will recognize also touch events?
This is the entire function:
//Auto-complete
$('#refn').keydown(function(e) {
if (e.keyCode == 40 || e.keyCode == 38) {
var current = $('#search-autocomplete .hover').parent();
if (current.length == 0)
$('#search-autocomplete li:first-child a').addClass('hover');
else {
current.find('a').removeClass('hover');
if (e.keyCode == 40) current.next().find('a').addClass('hover'); //Arrow down
else current.prev().find('a').addClass('hover'); //Arrow up
}
return false;
}
else if (e.keyCode == 13) {
if ($('#search-autocomplete .hover').length > 0) {
$('#refn').val($('#search-autocomplete .hover').data('ref'));
$('#search-autocomplete').hide();
}
event.preventDefault();
return false;
}
}).bind('keyup change', function(e) {
if ($(this).val().trim() == '' || $(this).data('autocompleted')) {
$(this).data('autocompleted', false);
return true;
}
// console.log($('#filter_brand').find(":selected").val());
$.ajax({
type: 'get',
url: '/subapp_cities/index.php/getsuggestions',
data: {
q: $('#refn').val() ,
ref: 1,
make: $('#filter_brand').find(":selected").val()
},
dataType: 'text',
success: function(response) {
response = eval('response = ' + response);
var selectedSuggestion = $('#search-autocomplete .hover').text();
$('#search-autocomplete').html('').show();
for (var i = 0; i < response.length; ++i){
var tag = response[i][1] + ' ' + response[i][0];
$('<li><a href="" data-ref="'+response[i][0]+'" ' + (tag == selectedSuggestion ? 'class="hover"' : '') + '>'+tag+'</a></li>').appendTo('#search-autocomplete');
}
},
error: function(request, status, error) {
console.error(status);
console.error(error);
}
});
});
Output:
. Explanation here: https://learn.jquery.com/events/event-delegation/. Let me know if all this is helpful and I’ll do a proper answer! :)
– Matt Saunders Apr 28 '19 at 21:29