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",
Related
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>
<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>
I have input of type text to which I have attached autocomplete:
javascript:
$("#descSearchBox").keyup(function(e) {
//$("#ui-id-1").addClass("dropdown-menu").removeClass('ui-autocomplete ui-front ui-menu ui-widget ui-widget-content ui-corner-all');
$(".ui-autocomplete").removeClass("ui-autocomplete ui-front ui-menu ui-widget ui-widget-content ui-corner-all")
.addClass('dropdown-menu');
$.post("/controls/DistControl.php", {
action: 'descAutocomplete',
description: $(this).val(),
myDistribution: $("#cbMyDistributions").is(":checked")
}, function(data) {
data = $.parseJSON(data);
$( "#titleSearchBox" ).val('');
console.log(data);
$( "#descSearchBox" ).autocomplete({
source: data.result.titles,
select: function( event, ui ) {
$("#titleSearchBox").val(ui.item.label);
distributionTableUpdate();
}
});
}
);
});
and here is php script that sends request back:
function descAutocomplete() {
$where['LIKE'] = [ "description" => $_POST['description'] ];
if( $_POST["myDistribution"] === "true" )
$where["user_id[=]"] = $_SESSION['user_id'];
$dists = DistributionModel::getAll( $where, 10, 0, 'title', 'ASC', [ 'title' ] );
$titles = [];
foreach($dists as $d) {
$titles[] = $d->get('title');
}
$response = new ResponseModel(ResponseModel::$TYPE_INFO, 'Description Autocomplete', [ 'titles' => $titles ]);
echo $response->encode();
}
The thing is I get result back, for example I just type 'e' in search and I get array with 4 elements but it shows nothing or just shows the last one. Why would do so? Why it does not shows all results?
Try to use Like
$("#name").autocomplete({
source: function( request, response ) {
$.ajax({
url: "URL",
dataType: "json",
data: {term: request.term},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.state,
id: item.id
};
}));
}
});
},
select: function(event, ui) {
$('#id').val(ui.item.id);
}
});
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.
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