Show hotels in autocomplete response - javascript

I have autocomplete input in my View.
Here is script, how I handle it
$(targetSelector).each(function() {
$(this)
.autocomplete({ delay: 10, minLength: 0, source(request, response) {
$(this.element[0]).attr("data-req-term", request.term);
$.ajax({
url: $(this.element[0]).attr("data-source"),
dataType: "json",
data: {
term: request.term
},
success(data) {
console.dir(data);
const results = [];
$.map(data.cities, function(value, key) {
results.push(value);
return $.map(value.airports, (value2, key2) =>
results.push(value2)
);
});
$.map(data.airports, (value, key) => results.push(value));
return response(results);
},
error() {
return response([]);
}
});
return null;
}, focus(event, ui) {
return false;
}, select(event, ui) {
const qel = $(event.currentTarget);
qel.val(ui.item.fullname);
$(qel.attr("data-id-element")).val(ui.item.id);
return false;
}
})
.data("ui-autocomplete")._renderItem = function(ul, item) {
return create_autocomplete_item($(this.element[0]), ul, item);
};
if (enableAutocompleteSelect) {
$(targetSelector).on("autocompleteselect",
function() {
if ($(this)[0].id.indexOf("origin") !== -1) {
const id = $(this)[0].id.split("_")[2];
$(`#search_legs_${id}_destination_text`).focus();
}
});
}
$(targetSelector).focus(function() {
$(this).keydown();
});
$(targetSelector).on("blur", function() {
const value = $(this).val() as string;
if (value.trim() == "") {
$(this).val("");
}
});
});
}
This function is using to get data for autocomplete. Aтв show airports and cities.
And here is answer from server, that I get.
I need to populate also hotels to autocomplete results.
How I can do this?

I can get values for Hotel just add this line
$.map(data.hotels, (value,key)=> results.push(value));

Related

jquery ui autocomplete custom data (item undefined )

My Script
$("#NameSearch").autocomplete({
minLength: 0,
source: function (request, response) {
$.ajax({
url: "/home/universalsearch/" + document.getElementById("filterUniversalSearchList").value + "/" + $("#NameSearch").val(),
type: "POST",
dataType: "json",
data: {
searchFilter: document.getElementById("filterUniversalSearchList").value,
term: request.term,
},
success: function (data) {
response($.map(data, function (item) {
return { label: item.EmployeeName, id: item.EmployeeID}
}))
}
});
},
focus: function (event, ui) {
$("#NameSearch").val(ui.item.label);
return false;
},
select: function (event, ui) {
$("#NameSearch").val(ui.item.label);
return false;
}
})
.autocomplete("instance")._renderItem = function (ul, item) {
return $("<li>")
.append("<div>" + item.label + "<br>" + item.id + "</div>")
.appendTo(ul);
};
});
Controller:
public JsonResult UniversalSearch(string searchFilter, string searchText)
{
var Employees = _home.GetEmployeeDetails(searchFilter, searchText);
return Json(new { data = Employees }, JsonRequestBehavior.AllowGet);
}
Problem I'm facing is in autocomplete dropdown I'm getting as undefined.
From controller it return as object array
I think I made mistake in binding data improperly.
dropdown result shows as undefined.
Is this problem due to jqueru-ui versions ?

jquery autocomplete, how to show all options on focous?

I have below autocomplete code, which works fine When i type one or more letters.
$("body").on('focus', 'input.sub-category', function () {
var id = $(this).data('thiscatid');
var term = $(this).val();
$(this).autocomplete({
minLength: 0,
source: function( request, response ) {
$.post( base_url + 'ajax/getSubCats',
{ parent_id: id, term: term},
function( data ) {
response(data);
},
'json'
);
},
select:function(event,ui){
$(".sub-cat").val(ui.item.label);
return false;
},
change: function(event, ui) {
console.log(this.value);
if (ui.item == null) {
this.setCustomValidity("You must select a category");
}
}
});
});
I would like to populate the drop down with all of the matching words from the database on just focusing the input box. That means even without typing a single word. When i just focus, the function is called, but nothing within the
function $(this).autocomplete({ is executed. Any idea why autocomplete not working when focus in on the input field?
Use below code it will work as per your requirement.
$("body input.sub-category").each(function{
$(this).on('focus', 'input.sub-category', function () {
var id = $(this).data('thiscatid');
var term = $(this).val();
$(this).autocomplete({
minLength: 0,
source: function( request, response ) {
$.post( base_url + 'ajax/getSubCats',
{ parent_id: id, term: term},
function( data ) {
response(data);
},
'json'
);
},
select:function(event,ui){
$(".sub-cat").val(ui.item.label);
return false;
},
change: function(event, ui) {
console.log(this.value);
if (ui.item == null) {
this.setCustomValidity("You must select a category");
}
}
});
});
});
If this is not work add status in comment.
I was able to fix by adding one more function. So there is one function executing on keyup and another one on focus.
$("body").on('keyup', 'input.sub-category', function () {
var id = $(this).data('thiscatid');
var term = $(this).val()?$(this).val():"";
$(this).autocomplete({
minLength: 0,
autoFocus: true,
source: function( request, response ) {
$.post( base_url + 'ajax/getSubCats',
{ parent_id: id, term: term},
function( data ) {
response(data);
},
'json'
);
},
select:function(event,ui){
$(this).val(ui.item.label);
return false;
},
change: function(event, ui) {
if (ui.item == null) {
this.setCustomValidity("You must select a category");
}
}
});
});
Above one executes on keyup and below one on focus.
$("body").on('focus', 'input.sub-category', function () {
var id = $(this).data('thiscatid');
var term = $(this).val()?$(this).val():"";
$(this).autocomplete({
minLength: 0,
autoFocus: true,
source: function( request, response ) {
$.post( base_url + 'ajax/getSubCats',
{ parent_id: id, term: term},
function( data ) {
response(data);
},
'json'
);
},
select:function(event,ui){
$(this).val(ui.item.label);
return false;
},
change: function(event, ui) {
if (ui.item == null) {
this.setCustomValidity("You must select a category");
}
}
});
$(this).autocomplete("search", "");
});

My object is undefined when I test it i QUnit

I'm using QUnit and have a test script for a JQuery UI Widget:
define(
['jquery',
'knockout',
'../Widget/SearchPod/searchPod',
'jqueryui',
'jquery.ui.widget',
'../Widget/SearchPod/clr.searchPod'],
function ($, ko, searchPod) {
var checkSearchBy = function () {
test('check if select has Search By text', function () {
var expected = "Search By";
alert(searchPod.employees);//.checkSearchByWidget());
deepEqual(searchPod.employees, expected, "We expect drop down text to
display 'Search By' by default");
return 1;
});
};
return {
checkSearchBy: checkSearchBy
};
}
);
For some reason whenever I run the test script, an error occurs saying that the parameter searchpod above is undefined or null. The code of searchpod is below:
require(['jquery',
'knockout',
'jqueryui',
'jquery.ui.widget',
'domReady!',
'Widget/SearchPod/clr.searchPod',
'Widget/Listbox/clr.combobox'],
function ($, ko) {
$(document).ready(function () {
$("#search-pod").searchPod({
ready: function () {
var minimumLength = 2;
$("#search-message").hide();
//start
//end
var employees = [*some data*]
var leaves_filed = [*some data*]
var claims_filed = = [*some data*]
function sortData(prop, asc) {
data = data.sort(function (a, b) {
if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
});
}
//This is to display search messages depends on selected search type and
function validateCriteria(selectedType) {
var searchMessage = 'No values match search criteria';
if (selectedType == 'ssn') {
if ($("#searchBox").val().length > minimumLength) {
searchMessage = 'Must enter all 9 digits of SSN';
}
}
$("#search-message").text(searchMessage);
}
// Search pod items
var selectedType = 'lastname';
var data = employees;
// Apply the combobox widget
$("#searchBy").combobox({
ready: function () {
},
select: function () {
selectedType = $("option:selected", this).val();
switch (selectedType) {
case 'lastname':
return;
if (employees.length == 1) {
$("#loadingImage").css("display", "");
$("#searchBox").css("display", "none");
$.ajax({
url: "api/Dashboard/GetEmployeeListReport",
type: "GET",
processData: false,
success: function (result) {
employees.length = 0;
employees = result.dataSet.dataTable.row;
$("#loadingImage").css("display", "none");
$("#searchBox").css({ display: '' });
data = employees;
}
});
}
else { data = employees; }
minimumLength = 1;
break;
case 'ssn':
minimumLength = 10;
break;
case 'eeid':
if (employees.length == 1) {
$("#loadingImage").css("display", "");
$("#searchBox").css("display", "none");
$.ajax({
url: "api/Dashboard/GetEmployeeListReport",
type: "GET",
processData: false,
success: function (result) {
employees.length = 0;
employees = result.dataSet.dataTable.row;
$("#loadingImage").css("display", "none");
$("#searchBox").css({ display: '' });
data = employees;
minimumLength = employees[5].eeid.length;
}
});
}
else { data = employees; minimumLength =
employees[5].eeid.length; }
break;
case 'leave_number':
if (leaves_filed.length == 1) {
$("#loadingImage").css("display", "");
$("#searchBox").css("display", "none");
$.ajax({
url: "api/Dashboard/GetLeavesList",
type: "GET",
processData: false,
success: function (result) {
leaves_filed.length = 0;
leaves_filed = result.dataSet.dataTable.row;
$("#loadingImage").css("display", "none");
$("#searchBox").css({ display: '' });
data = leaves_filed;
minimumLength = leaves_filed[0].leaveNumber.length;
}
});
}
else { data = leaves_filed; minimumLength =
leaves_filed[0].leaveNumber.length; }
break;
case 'claim_number':
if (claims_filed.length == 1) {
$("#loadingImage").css("display", "");
$("#searchBox").css("display", "none");
$.ajax({
url: "api/Dashboard/GetClaimsList",
type: "GET",
processData: false,
success: function (result) {
claims_filed.length = 0;
claims_filed = result.dataSet.dataTable.row;
$("#loadingImage").css("display", "none");
$("#searchBox").css({ display: '' });
data = claims_filed;
minimumLength = claims_filed[10].claimNumber.length;
}
});
}
else { data = claims_filed; minimumLength =
claims_filed[10].claimNumber.length; }
break;
}
sortData(selectedType, true);
$('#searchBox').val('');
}
});
sortData(selectedType, true);
//This will hide search-message when backpress is pressed.
$('html').keyup(function (e) {
if (e.keyCode == 8) {
if ($("#searchBox").val().length < minimumLength) {
if ($("#search-message").show()) $("#search-message").hide();
}
}
return;
});
//Code for Making SSN AutoComplete
$('#searchBox').keyup(function () {
if (selectedType == "ssn" && $('#searchBox').val().length == 10) {
var rptParam = "?ssn=" + $('#searchBox').val();
var ssnData = [{ "ssn": "", "lastname": "" }];
$.ajax({
url: "api/Dashboard/GetSsnList" + rptParam,
type: "GET",
processData: false,
success: function (result) {
ssnData = result.dataSet.dataTable.row;
var ssnArray = [];
ssnArray.push(ssnData);
if (ssnArray.length > 0) {
$("#searchBox").autocomplete({
minLength: 10,
source: function (request, response) {
var searchField;
var filteredArray = $.map(ssnArray, function (item) {
if (item.ssn != null) {
searchField = item.ssn;
if (searchField.toLowerCase().indexOf
(request.term) == 0 || searchField.indexOf
(request.term) == 0) {
return item;
}
} else { return null; }
});
response(filteredArray);
},
focus: function (event, ui) {
var focusValue;
focusValue = ui.item.ssn;
$("#searchBox").val(focusValue);
return false;
},
select: function (event, ui) {
}
}).data("ui-autocomplete")._renderItem =
function (ul,item){
return $("<li>")
.append(displayFormat)
.appendTo(ul);
};
}
$('#searchBox').autocomplete("search");
}
});
}
return;
});
$("#searchBox").focus(function () {
if (selectedType == 'ssn') {
$("#searchBox").autocomplete();
$("#searchBox").autocomplete("destroy");
return;
}
var searchField;
$("#searchBox").autocomplete({
minLength: minimumLength,
source: function (request, response) {
var filteredArray = $.map(data, function (item) {
if (selectedType === 'lastname') {
searchField = item.lastname;
}
if (selectedType === 'ssn') {
return false;
}
if (selectedType === 'eeid') {
searchField = item.eeid;
}
if (selectedType === 'leave_number') {
searchField = item.leaveNumber;
}
if (selectedType === 'claim_number') {
searchField = item.claimNumber;
}
if (searchField.toLowerCase().indexOf(request.term) == 0 ||
searchField.indexOf(request.term) == 0) {
if (selectedType === 'ssn' && request.term.length < 4) {
return null;
}
return item;
}
else {
return null;
}
});
if (!filteredArray.length) {
$("#search-message").show();
validateCriteria(selectedType);
}
else {
$("#search-message").hide();
}
response(filteredArray);
},
focus: function (event, ui) {
var focusValue;
if (selectedType === 'lastname') {
focusValue = ui.item.lastname;
}
if (selectedType === 'eeid') {
focusValue = ui.item.eeid;
}
if (selectedType === 'leave_number') {
focusValue = ui.item.leaveNumber;
}
if (selectedType === 'claim_number') {
focusValue = ui.item.claimNumber;
}
$("#searchBox").val(focusValue);
return false;
},
create: function (event, ui) {
$(this).autocomplete("widget").addClass("search-results-list");
},
open: function (event, ui) {
$(".search-results-list li.ui-menu-item").addClass("search-results-item");
},
select: function (event, ui) {
//return false; // Cancel the select event
var focusValue;
if (selectedType === 'lastname') {
focusValue = ui.item.lastname;
// TODO: call a function here that will send the name of the report to show
$('#report-popup-dialog-overlay').show();
$('#report-popup-dialog').show();
}
if (selectedType === 'eeid') {
focusValue = ui.item.eeid;
}
if (selectedType === 'leave_number') {
focusValue = ui.item.leaveNumber;
$('#dynamictext').text('Leave Report for ' + focusValue);
$('#dynamicHeader').text('Leave Report');
}
if (selectedType === 'claim_number') {
focusValue = ui.item.claimNumber;
$('#dynamicHeader').text('Claim Report for ' + focusValue);
$('#dynamictext').html("Loading...");
//Need to make Ajax Call to get the report.
var parameter = "?claimNumber=" + focusValue;
$.ajax({
url: "api/ViewReport/GetClaimReport" + parameter,
type: "POST",
processData: false,
success: function (result) {
$('#dynamictext').html("");
$('#dynamictext').html(result);
}
});
}
return false;
}
})
.data("ui-autocomplete")._renderItem = function (ul, item) {
var displayFormat = "";
return $("<li>")
.append(displayFormat)
.appendTo(ul);
};
});
}
});
});
//Test helper functions
//2. checkSearchBy
function checkSearchBy() {
alert($('#searchBy').text());
return $('#searchBy').text();
}
return {
checkSearchByWidget: function () {
return checkSearchBy();
}
};
});
I've been at this for two days but cant seem to make the searchpod be seen by the test script above

How to close autocomplete dropdown on side click

I user jquery autocomplete to fetch some results and results are displayed but when I click on the side can't close dropdown with returned results.
$(function () {
$("#search").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("TestAutoComplete", "Home")', type: "POST", dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Title
};
}));
}
});
},
minLength: 1,
select: function (event, ui) {
onItemSelect(ui.item);
},
open: function () {
$(this).removeClass('ui-corner-all').addClass('ui-corner-top');
$(this).autocomplete('widget').css('z-index', 999999);
},
close: function () {
$(this).removeClass('ui-corner-top').addClass('ui-corner-all');
}
})
.data('ui-autocomplete')._renderItem = function (ul, item) {
return $('<li>')
.data('autocomplete-item', item)
.append('<p >' + item.label + "</p>")
.appendTo(ul);
};
});
Very stupid error.
$("#search").autocomplete({...
it should be
$(".search").autocomplete({...
and it work.
Your markup isn't totally clear to me from just looking at your js but it would be something like this:
$("html").on("click.autocomplete", function(e){
var $targ = $(e.target || event.srcElement);
if ( !$targ.is( /* searchlist */ ) || !$( /* searchlist */ ).has( $targ ).length ) {
//Close autocomplete
$("html").off(".autocomplete");
}
});
You leave us somehow blinded of your implementation, but assuming a good pattern the solution would be, detect on every click on the document if the element that was clicked (e.target) ) is inside the search else close the searchbox.
$(document).on('click', function(e)
{
var jqTarget = $(e.target);
if ( !jqTarget.closest('#search').length )
{
$("#search").hide();
}
});
var that = $('.autocomplete'); //Define this somewhere in the page to refer later
$('document').on('mousedown', function(e){
if ($(e.target).closest('.autocomplete:not(:visible)').length != 0) {
that.hide();
}
});

jQuery Autocomplete can't replace only part of input value

I am trying to make autocomplete like on Github.
We have a textarea where we write in it some text. We also put -> '#' and try to auto complete a username.
When we the autocomplete script runs it removes all of the text.
My script:
function getSign(text){
var indexOfAt = text.lastIndexOf('#');
return indexOfAt;
};
function changeText(event, ui) {
var selectedElement = event.target.innerText;
var text = $(this).val();
text.replace(/#$/ , selectedElement);
$(this).val(text);
}
$(document).ready(function() {
$("textarea#autocomplite").autocomplete({
source: function(request, response) {
$.ajax({
url: "/feeds/autocomplite_search",
data: {
term: request.term.substr(getSign(request.term)+1,request.term.length-getSign(request.term)).trim()
},
success: function(data){
for(i=0; i<data.length; i++){
data[i] = '#'+data[i];
}
return response(data);
}
});
},
minLength: 2,
delay: 400,
disabled: true,
search: function() {
if ( /\s$/.test($(this).val()) ) {
$(this).autocomplete('disable');
};
},
select: changeText
});
$("textarea#autocomplite").keyup(function() {
if ( /#$/.test($(this).val()) ) {
$(this).autocomplete('enable');
};
});
});
replace does not modify the original. Reassign:
text = text.replace(/#$/ , selectedElement);

Categories

Resources