Start autocomplete when press any keyword in input field - javascript

Autocomplete is not working when there is some text in input field and I want that it should work in that input field at any time when I press any keyword(e.g '#').
I am able to do the search part it is showing in the log but on page its not visible, its only visible if the input field is empty.

you can see this example.
i think it could help you a
<input type="text" name="autocomplete" id="globalBCCAutoComplete" value="john">
$(document).ready(function() {
let countries = [
{ value: '{contract_name}', data: 'Contact Name'},
{ value: '{user_company}', data: 'User Company' }
];
//get current value from the textbox
let initialTextValue = $('#globalBCCAutoComplete').val().trim();
//append the values to the json object.
$(countries).each(function(key, country) {
country.value = initialTextValue + ' ' + country.value
});
//the rest of your code:
$('#globalBCCAutoComplete').autocomplete({
lookup: countries,
onSelect: function (suggestion) {
console.log('You selected: ' + suggestion.value + ', ' + suggestion.data);
}
});
});

Related

Store previous kendo dropdownlist option using keyboard

I want to store the previously selected option when navigating with the keyboard. I have achieved this if the user clicks on the drop down but it doesn't store the option if navigated with the keyboard.
Code:
CreateDropDown: function (id) {
var me = IndexController;
$("#Drop" + id + "").kendoDropDownList({
name: "drop" + id,
dataTextField: "text",
dataValueField: "value",
valueTemplate: '<i class="#:data.icon#"> </i></span><span>#:data.text#</span>',
template: '<i class="#:data.icon#"> </i>' +
'<span class="k-state-default"><p>#: data.text #</p></span>',
dataSource: me.variable.options,
index: 0,
change: me.onChange,
open: function (e) {
me.options.previousOption = e.sender.value();
}
});
me.AddShortText(id, "Short Answer");
}
and I can use the value:
AddShortText: function (a, ChoiceText) {
var me = IndexController;
if (me.options.previousOption == "2" || me.options.previousOption == "3")
$("#TypeDiv" + a).children(".toRemove").remove();
else
$("#TypeDiv" + a).children(".group").remove();
$("#TypeDiv" + a).append('<div class="group" style="width:50%">\
<input id="Answer'+ a + '" type="text" class="inputHighlight" disabled >\
<span class="bar"></span>\
<label class="labelHighlight">'+ ChoiceText.trim() + '</label>\
</div>');
},
GIF:
Thank you in advance
Use the select event https://docs.telerik.com/kendo-ui/api/javascript/ui/dropdownlist/events/select
The select function is triggered both with keys or mouse
$("#Drop").kendoDropDownList({
// your code
select: function(e) {
me.options.previousOption = e.sender.value();
}
});

ajax autocomplete same data with multiple textbox jquery

i have one issue with jquery autocomplete, its working with one textbox perfect but when i create multiple textbox using jquery with same ID at that time its working for only first textbox not for another textbox .
my question is i want to create multiple textbox and implement same autocomplete data with all text box
this is my code for create textbox using jquery
var totalSelect = $('#max_player').val();
$('#competitor_box').empty();
for (var i = 1; i <= totalSelect; i++) {
var ajaxauto = '<div class="form-group col-sm-3"><label for="tournament_name">Pocker # '+i+'</label><input id="autocomplete-ajax" type="text" class="form-control" autocomplete="off"></div>';
$('#competitor_box').append(ajaxauto);
}
this code for ajax autocomplete
$('#autocomplete-ajax').autocomplete({
// serviceUrl: '/autosuggest/service/url',
lookup: countriesArray,
lookupFilter: function(suggestion, originalQuery, queryLowerCase) {
var re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi');
return re.test(suggestion.value);
},
onSelect: function(suggestion) {
$('#selction-ajax').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
},
onHint: function (hint) {
$('#autocomplete-ajax-x').val(hint);
},
onInvalidateSelection: function() {
$('#selction-ajax').html('You selected: none');
}
});
please help me for this issue its very important for me
thanks all.
var totalSelect = $('#max_player').val();
$('#competitor_box').empty();
for (var i = 1; i <= totalSelect; i++) {
var ajaxauto = '<div class="form-group col-sm-3"><label for="tournament_name">Pocker # '+i+'</label><input class="txtAutocomplete" type="text" class="form-control" autocomplete="off"></div>';
$('#competitor_box').append(ajaxauto);
}
Autocomplete function
$('.txtAutocomplete').autocomplete({
// serviceUrl: '/autosuggest/service/url',
lookup: countriesArray,
lookupFilter: function(suggestion, originalQuery, queryLowerCase) {
var re = new RegExp('\\b' + $.Autocomplete.utils.escapeRegExChars(queryLowerCase), 'gi');
return re.test(suggestion.value);
},
onSelect: function(suggestion) {
$('#selction-ajax').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
},
onHint: function (hint) {
$('#autocomplete-ajax-x').val(hint);
},
onInvalidateSelection: function() {
$('#selction-ajax').html('You selected: none');
}
});
why did you use the same ID for severals input ? use classes if you have to tag multiples elements, for example .autocomplete-ajax-input on each textbox. And then declare your autocomple function with $('.autocomplete-ajax-input').autocomplete

Why Typeahead shows json object in input after click

My suggestion engine works fine, I just have a problem because when I click on item its json object appears in input element. I would like only OrgName to appear in input value.
<input class="form-control companySearch" type="text" value="" name="q" autocomplete="off" placeholder="Search a company">
var organization = new Bloodhound({
remote: {
url: '/search/org?term=%QUERY%',
wildcard: '%QUERY%'
},
datumTokenizer: Bloodhound.tokenizers.whitespace('term'),
queryTokenizer: Bloodhound.tokenizers.whitespace
});
$(".companySearch").typeahead({
hint: true,
highlight: true,
minLength: 1,
},
{
source: organization.ttAdapter(),
name: 'organizationsList',
templates: {
suggestion: function (data) {
return '<a class="list-group-item ">' + data.OrgName + ', '+ data.address.Address+ ', '+ data.address.city.City+ ', ' + data.address.city.country.Country + '</a>';
}
}
}
);
I had a similar problem and solved it using the typeahead's display attribute.
In your example:
$(".companySearch").typeahead({
hint: true,
highlight: true,
minLength: 1,
},
{
source: organization.ttAdapter(),
name: 'organizationsList',
display: 'id', // PUT IT HERE
templates: {
suggestion: function (data) {
return '<a class="list-group-item ">' + data.OrgName + ', '+ data.address.Address+ ', '+ data.address.city.City+ ', ' + data.address.city.country.Country + '</a>';
}
}
}
);
From the docs:
display – For a given suggestion, determines the string representation of it. This will be used when setting the value of the input control after a suggestion is selected. Can be either a key string or a function that transforms a suggestion object into a string. Defaults to stringifying the suggestion.
If it doesn't work, try replace display for displayKey (I think that is something on the typeahead's versions).

typeahead not updating field

I am trying to implement typeahead for a city look-up for, but the field does not get updated. The city details show up, but I need to show the name in the city when a city is clicked, but when the form is sent, I need to send only the city code.
This is my HTML:
<input id="_hotelCity" class="form-control typehead" type="text" value="" placeholder="Enter city name or code " />
And this is the javascript:
$('#_hotelCity').typeahead({
source: function (query, process) {
airports = [];
map = {};
var data = (function () {
var data = null;
$.ajax({
'async': false,
'global': false,
'url': 'http://localhost/imakeway/forms/finder/iata-aero-codes.json',
'dataType': "json",
'success': function (jdata) {
data = jdata;
}
});
return data;
})();
$.each(data, function (i, airport) {
map[airport.complete_location] = airport;
airports.push(airport.city + ' ( <b>' + airport.iata_code + '</b> - ' + airport.airport_name + ') near ' + airport.complete_location);
});
process(airports);
},
updater: function (item) {
selectedairport = map[item].complete_location;
selectedairport = map[item].iata_code;
return item;
},
matcher: function (item) {
if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
},
sorter: function (items) {
return items.sort();
},
highlighter: function (item) {
var regex = new RegExp( '(' + this.query + ')', 'gi' );
return item.replace( regex, "<strong>$1</strong>" );
},
});
Thank you for any suggestions
HTML input tag can have only one value. This value is stored internally and displays inside the field.
It seems you are using some kind of AJAX form submission.
So, your solution is to have separate variable in JS to store city code.
Another solution is to use Select2 instead of typeahead.
This is my choice when you provide a SELECT-like field but need external AJAX data source.
Btw, with Select2 you can also force user to choose only an existing value.
Look here for example: http://ivaynberg.github.io/select2/#ajax
I would suggest you to use an additional hidden field which you update aside the normal input field.
<input id="_hotelCity" class="form-control typehead" type="text" value="" placeholder="Enter city name or code " />
<input type="hidden" value="" name="city_code" />
In this hidden field you put the city code eachtime the typeahead is updated. When submitting the form your server side script can parse it (in PHP it would $_POST['city_code']).
Using typeahead, and didnt want to replace very much of your code. I ended up with this fiddle: http://jsfiddle.net/Ydtq9/2/
You will definitely want to refactor some things but the trick is to set some instance variables in the source function, and you can access them in the updater function like so
$("#_hotelCity").typeahead({
"source": function(query, process) {
this.map = ...
},
"updater": function(item) {
var city = this.map(item)
//Then you can do what you need to with the original data.
}
})

Read selected node's values from kendo tree view?

I have a kendo treeview having a node with {id, value}. and I want to get selected node's id and value when I click on a button.
How can I get it? Is there any inbuilt functions there to get it?
Here is my sample code:
$("mytree").kendoTreeView({
dataSource: mydata,
dataTextField: "Name",
dataValueField: "Id",
});
Use the .select() method. Be sure to look at the other methods available as well.
var tv = $('.mytree').data('kendoTreeView'),
selected = tv.select(),
item = tv.dataItem(selected);
if (item) {
alert('Selected item: ' + item.Name + ' : ' + item.Id + ' (uid: ' + item.uid + ')');
} else {
alert('Nothing selected');
}
Fiddle here
**
var tv = $("#treeview-right").data("kendoTreeView");
var selectedNode = tv.select();
var item = tv.dataItem(e.node);
item.text will give you the text of the selected node.
**
I disagree with the selected answer because depending on what you actually DO, you can be 1 step behind the actually selected value.
If you had some simple delete function then this type of code works fine
var treeview = $("#treeview").data("kendoTreeView");
var selectedNode = treeview.select(),
item = treeview.dataItem(selectedNode);
However, once you start playing with the treeview more you will end up regretting that as I have.
Best practice is to tie to the event handler
e.g.
var treeview = $("#treeview").kendoTreeView({
expanded: true,
select: onSelect,
....
}).data("kendoTreeView");
select function
function onSelect(e) {
var treeview = $("#treeview").data("kendoTreeView");
var item = treeview.dataItem(e.node);
if (item) {
console.log('Selected item: ' + item.whatever + ' | Id = ' + item.Id + ' | Type = ' + item.Type);
var someVariable = item.whatever;
} else{
console.log('nothing selected');
}

Categories

Resources