let searchResult = document.querySelector('input[name="search"]');
searchResult.addEventListener('keyup', function(e) {
let cityName = $(this).val(),
searchInput = $(this),
formAction = $(this).parent().attr('action'),
formMethod = $(this).parent().attr('method'),
resultBox = $(this).parent().parent().find('.search-form-result');
searchRequest = $.ajax({
url: formAction,
method: formMethod,
data: {'cityName': cityName},
dataType: 'html',
}).done(function (data) {
if (data) {
searchInput.addClass('active');
resultBox.find('.scrollbar-search-form-result').html(data);
resultBox.show();
if (e.keyCode == 38 || e.code == 'ArrowUp') {
e.preventDefault();
let last = document.querySelector('.search-form-result-city:last-child');
last.className += ' selected-city';
}
if (e.keyCode == 40 || e.code == 'ArrowDown') {
e.preventDefault();
let first = document.querySelector('.search-form-result-city:first-child');
first.className += ' selected-city';
}
} else {
resultBox.hide();
searchInput.removeClass('active');
}
});
});
let searchRequest = null,
searchResult = document.querySelector('input[name="search"]');
searchResult.addEventListener('keyup', function(e) {
let cityName = $(this).val(),
searchInput = $(this),
formAction = $(this).parent().attr('action'),
formMethod = $(this).parent().attr('method'),
resultBox = $(this).parent().parent().find('.search-form-result'),
searchForm = $('.search-form-result-city');
if (searchForm.hasClass('selected-city') && (e.keyCode == 38 || e.keyCode == 40)) {
return false;
}
if (searchRequest !== null) {
searchRequest.abort();
}
searchRequest = new XMLHttpRequest();
searchRequest.open(formMethod, formAction + "?cityName=" + cityName, true);
searchRequest.onload = function() {
if (this.status >= 200 && this.status < 400) {
let data = this.response;
searchInput.addClass('active');
resultBox.find('.scrollbar-search-form-result').html(data);
resultBox.show();
if (e.keyCode === 13) {
let url = $.parseHTML(data)[1]['children'][0]['attributes'][0]['value'];
if (url) {
window.location = url;
return false;
}
}
if (!searchForm.hasClass('selected-city') && e.code == 'ArrowUp') {
let last = document.querySelector('.search-form-result-city:last-child');
last.className += ' selected-city';
}
if (!searchForm.hasClass('selected-city') && e.code == 'ArrowDown') {
let first = document.querySelector('.search-form-result-city:first-child');
first.className += ' selected-city';
}
} else {
resultBox.hide();
searchInput.removeClass('active');
}
}
searchRequest.send();
});