Jquery autocomplete from json array - javascript

Please solve this issue:
I have the json format array in external js: (NOT Ajax(json) request)
var data = [{"Id": 0,"City": "Chicago"},{"Id": 1,"City": "New York"},...]
I need to create Jquery autocomplete form with arrow. Maybe it will be:
select
Chicago (from external JS)
New York
/select,
or textarea, input. One thing is required: arrow will be visible, because user may choose elements with mouse.
How to attach array to html page?
Image

Here it shows all the items containing the word in input. Check this fiddle. May it helps.
var data = [{"Id": 0,"City": "Chicago"},
{"Id": 1,"City": "New York"},
{"Id": 2,"City": "Aew York1"},
{"Id": 3,"City": "Bew York2"}]
$.each(data,function(i,item){
var $option=$('<option>',{val:item.Id,text:item.City});
$('#tags').append($option);
})
$.widget( "custom.combobox", {
_create: function() {
this.wrapper = $( "<span>" )
.addClass( "custom-combobox" )
.insertAfter( this.element );
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function() {
var selected = this.element.children( ":selected" ),
value = selected.val() ? selected.text() : "";
this.input = $( "<input>" ).appendTo( this.wrapper )
.val( value )
.attr( "title", "" )
.addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy( this, "_source" )
})
.tooltip({
classes: {
"ui-tooltip": "ui-state-highlight"
}
});
this._on( this.input, {
autocompleteselect: function( event, ui ) {
ui.item.option.selected = true;
this._trigger( "select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function() {
var input = this.input,
wasOpen = false;
$( "<a>" )
.attr( "tabIndex", -1 )
.attr( "title", "Show All Items" )
.tooltip()
.appendTo( this.wrapper )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "custom-combobox-toggle ui-corner-right" )
.on( "mousedown", function() {
wasOpen = input.autocomplete("widget").is( ":visible" );
})
.on( "click", function() {
input.trigger("focus");
// Close if already visible
if ( wasOpen ) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete( "search", "" );
});
},
_source: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
response( this.element.children( "option" ).map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) )
return {
label: text,
value: text,
option: this
};
}) );
},
_removeIfInvalid: function( event, ui ) {
// Selected an item, nothing to do
if ( ui.item ) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children( "option" ).each(function() {
if ( $( this ).text().toLowerCase() === valueLowerCase ) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if ( valid ) {
return;
}
// Remove invalid value
this.input.val( "" ).attr( "title", value + " didn't match any item" ).tooltip("open");
this.element.val( "" );
this._delay(function() {
this.input.tooltip( "close" ).attr( "title", "" );
}, 2500 );
this.input.autocomplete( "instance" ).term = "";
},
_destroy: function() {
this.wrapper.remove();
this.element.show();
}
});
$( "#tags" ).combobox();
.custom-combobox {
position: relative;
display: inline-block;
}
.custom-combobox-toggle {
position: absolute;
top: 0;
bottom: 0;
margin-left: -1px;
padding: 0;
}
.custom-combobox-input {
margin: 0;
padding: 5px 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div>
<label for="tags">Tags: </label>
<select id="tags"></select>
</div>

Related

jquery autocomplete multiple input groups

<form id="form1">
<input type="text" name="idEmp[]" class="idEmp">
<input type="text" name="nameEmp[]" class="nameEmp">
<input type="text" name="idEmp[]" class="idEmp">
<input type="text" name="nameEmp[]" class="nameEmp">
</form>
and the jquery here
$('.idEmp').on("focus", function(){
$(this).autocomplete({
minLength: 1,
source: "autocomplete.php",
focus: function(event, ui){
$(this).val(ui.item.id);
return false;
},
select: function(event, ui){
$(this).val(ui.item.id);
// something else here to show name in nameEmp fields
return false
}
})
.autocomplete("instance")._renderItem = function(ul, item){
return $("<li class='list-group-item list-group-item-info'>")
.append("<a><h5>Emp. ID : "+item.id+"<br><span class='badge'>"+item.name+"</span></h5></a>")
.appendTo(ul);
};
});
i want to apply jQuery autocomplete in each idEmp class then value of ID appears in idEmp[] and value name appears in nameEmp[]. is there anyone know this? thanks in advance!
Start typing jQuery and select the autocomplete option then fields would be populated with label and description, use below code as reference to your code.
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
$( ".idEmp" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( this ).val( ui.item.label );
$( this ).next( ".nameEmp" ).val( ui.item.desc );
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css"></link>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
Start typing jQuery and select the autocomplete option
<form id="form1">
<input type="text" name="idEmp[]" class="idEmp">
<input type="text" name="nameEmp[]" class="nameEmp"><br/>
<input type="text" name="idEmp[]" class="idEmp">
<input type="text" name="nameEmp[]" class="nameEmp">
</form>

How to implement my own rule in filter result in jQuery UI Autocomplete

This is my code:
var projects = [{label:"PH2938", value: "1", fk: "3", desc: "hello"},
{label:"JUH28", value: "2", fk: "0", desc: "world"},];
{label:"HK383", value: "3", fk: "3", desc: "!"},];
$( "#serial_no" ).autocomplete({
minLength: 0,
source: function(request, response) {
var results = $.ui.autocomplete.filter(projects, request.term);
response(results);
},
focus: function( event, ui ) {
$( "#serial_no" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#serial_no" ).val( ui.item.label );
$( "#device_id" ).val( ui.item.value );
$( "#device_model" ).text( ui.item.desc );
return false;
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
So now, for example, if I type 'H' in the field, all 3 results (i.e PH2938, JUH28, HK383) will be shown. My question is: is possible to make it only show the results (i.e. PH2938, HK383) whose fk = 3. That is, can I implement my own rule in showing which results.
If I have understood correctly you need to filter the projects by some criteria. In this case by fk being equal to '3'.
As you are already using jQuery then $.grep is the good candidate for the filtering task.
$.grep(projects, function (project) {
return project.fk === '3';
});
Now we have to decide where to perform this filtering.
If you want to get rid of those projects that meet the fk criteria regardless of the term used in the autocompletion input, I would do it in the original projects array:
var projects = [{label:"PH2938", value: "1", fk: "3", desc: "hello"},
{label:"JUH28", value: "2", fk: "0", desc: "world"},];
{label:"HK383", value: "3", fk: "3", desc: "!"},];
projects = $.grep(projects, function (project) {
return project.fk === '3';
});
If what you want is something more flexible that allows you to provide a different data source depending on other criteria, not only the text matching of the label, then you can perform this filtering in the source property:
source: function(request, response) {
var results = $.ui.autocomplete.filter(projects, request.term);
// Filter the matched results by project fk 3.
results = $.grep(results, function (project) {
return project.fk === '3';
});
response(results);
},
The filtering could be performed before the matching too:
source: function(request, response) {
// Filter the matched projects by project fk 3.
var filteredProjects = $.grep(projects, function (project) {
return project.fk === '3';
});
var results = $.ui.autocomplete.filter(filteredProjects, request.term);
response(results);
},
See a demo for the latter.

Jquery autocomplete doesn't work

I got the following code from jquery ui demo.
I did some minor modifications to that.
Here is the modified code.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Custom data and display</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!--link rel="stylesheet" href="/resources/demos/style.css"-->
<style>
#project-label {
display: block;
font-weight: bold;
margin-bottom: 1em;
}
#project-description {
margin: 0;
padding: 0;
}
</style>
<script>
$(function() {
var projects = [
{
id: "jquery",
name: "jQuery",
location: "the write less, do more, JavaScript library"
},
{
id: "jquery-ui",
name: "jQuery UI",
location: "the official user interface library for jQuery"
},
{
id: "sizzlejs",
name: "Sizzle JS",
location: "a pure-JavaScript CSS selector engine"
}
];
$( "#project" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.name );
return false;
},
select: function( event, ui ) {
$( "#project" ).val( ui.item.name );
$( "#project-id" ).val( ui.item.id );
$( "#project-description" ).html( ui.item.location );
return false;
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.name + "<br>" + item.location + "</a>" )
.appendTo( ul );
};
});
</script>
</head>
<body>
<div id="project-label">Select a project (type "j" for a start):</div>
<input id="project">
<input type="hidden" id="project-id">
<p id="project-description"></p>
</body>
</html>
Now jquery pops up autocomplete suggestions only when 'j' key is pressed.
for other keys it doesn't do anything.
what am I doing wrong here?
It is because of the default search mechanism, it filters the contents based on the fields label or value.
With your custom data, it is better to implement the source method yourself like,
$("#project").autocomplete({
minLength: 0,
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
var array = $.grep(projects, function (value) {
return matcher.test(value.id) || matcher.test(value.name) || matcher.test(value.location);
});
response(array);
},
focus: function (event, ui) {
$("#project").val(ui.item.name);
return false;
},
select: function (event, ui) {
$("#project").val(ui.item.name);
$("#project-id").val(ui.item.id);
$("#project-description").html(ui.item.location);
return false;
}
})
.data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.append("<a>" + item.name + "<br>" + item.location + "</a>")
.appendTo(ul);
};
Demo: Fiddle
You must have a value attribute on your projects array:
var projects = [
{
id: "jquery",
name: "jQuery",
value:"jQuery",
location: "the write less, do more, JavaScript library"
},
...
{
id: "sizzlejs",
name: "sizzle JS",
value:"sizzle JS",
location: "a pure-JavaScript CSS selector engine"
}
];
This way the search engine is going to work.

Alter Ajax Json Query Parameter [duplicate]

This question already has answers here:
How do you pass multiple parameters of the same type to jQuery Get
(5 answers)
Closed 9 years ago.
This is my current code: http://jsfiddle.net/spadez/nHgMX/2/
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 7,
name_startsWith: request.term,
country: "UK"
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 1,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
This link states this: http://www.geonames.org/export/geonames-search.html
featureclass(es) (default= all feature classes); this parameter may
occur more than once, example: featureClass=P&featureClass=A
How can I adjust my code to set the feature class to A and P not just P as it is currently?
I find 2 solutions:
First one is use method suggested by #George Cummins:
jQuery.ajaxSettings.traditional = true;
...
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: ["A","P"],
In second you can add parameters to query string:
$.ajax({
url: "http://ws.geonames.org/searchJSON?featureClass=A&featureClass=P", // you can concantenate it

jQuery UI autocomplete jsonp mapping response

I am trying to use the autocomplete from jqueryUI. When i alert the response i get the following : ([ { "id": "test", "label": "test", "value": "test" } ]);
but when i try to map the result the dropdown result is empty. here is my code:
<script>
$(function() {
function log( message ) {
$( "<div/>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://localhost/jQuery/development-bundle/demos/autocomplete/search3.php",
jsonp: "jsonp_callback",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
alert(data);
response( $.map( data, function( item ) {
return {
label: item.label,
value: item.value
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
</script>
my server side script uses the following code:
echo $_GET['jsonp_callback'] . '(' . $data . ');';
Thanks anyway
use this line
url: "http://ws.geonames.org/searchJSON?jsonp_callback=?",
and datatype also
dataType: 'jsonp',
instead of
url: "http://ws.geonames.org/searchJSON",

Categories