jquery autocomplete does not shows result - javascript

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);
}
});

Related

How to import JSON object with arrays into ajax autocomplete response?

A company email-generating application I'm working on has an autocomplete input to autofill email theme data into a form. The data is returned as a JSON object, but a couple of the object values extraps and extraul contain multidimensional arrays. I'm able to get the plain key:value data just fine out in the response, but I can't seem to figure out how to pull the arrays in so I can loop over them to update certain sections of the form.
Here's a look at some of the JSON code coming in:
0:
emaildate: "2019-01-10"
extraps: Array(2)
0: {extrap: "test paragraph", position: 1}
1: {extrap: "another paragraph", position: 3}
length: 2
__proto__: Array(0)
extraul: Array(4)
0: {ulid: 1, position: 2, li: "list item 1", liposition: 1}
1: {ulid: 1, position: 2, li: "list item 2", liposition: 2}
2: {ulid: 1, position: 2, li: "list item something new", liposition: 3}
3: {ulid: 1, position: 2, li: "A new list item", liposition: 4}
length: 4
__proto__: Array(0)
id: 44
label: "Some Kind of Email Theme - 2019-01-10"
lastupdated: "2019-01-06 02:00:04"
store: "Premier"
themedesc: "Here's a description of the theme."
themeimage: null
themeincludeextrap: 1
themeincludeul: 1
themelink: "some-kind-of-email-theme"
themelinkinclude: 1
themename: "Some Kind of Email Theme"
themenotes: "Some notes about it"
themesortorder: 0
value: "Some Kind of Email Theme"
__proto__: Object
length: 1
__proto__: Array(0)
And here's a look at the javascript to bring it in from autotheme.php:
//Autofill Theme Info based on text entry
$( "#themename" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "autotheme.php",
type: "GET",
dataType: "json",
data: {
q: request.term
},
success: function(data) {
console.log(data);
response($.map(data, function(item) {
return {
id: item.id,
value: item.value,
label: item.label,
themename: item.themename,
themenotes: item.themenotes,
themedesc: item.themedesc,
themeimage: item.themeimage,
themeincludeextrap: item.themeincludeextrap,
themeincludeul: item.themeincludeul,
themelinkinclude: item.themelinkinclude,
themelink: item.themelink,
themeextraps: item.extraps,
themeextraul: item.extraul
}
}))
},
error: function(errorThrown){
console.log(errorThrown);
console.log("There is an error with theme autocomplete.");
}
});
},
minLength: 2,
select: function(event, ui) {
if (ui.item) {
$this = $(this);
$('#themeid').val('');
$('#extratext').html('');
$('#themename').val(ui.item.themename);
$('#themenotes').val(ui.item.themenotes);
$('#themedesc').val(ui.item.themedesc);
var themeimage = ui.item.themeimage;
var themeincludeextrap = ui.item.themeincludeextrap;
var themeincludeul = ui.item.themeincludeul;
var themelinkinclude = ui.item.themelinkinclude;
var themeextraps = ui.item.extraps;
var themeextraul = ui.item.extraul;
if(themeextraps !== undefined) {
var extrapcount = themeextraps.length;
}
if(themeextraul !== undefined) {
var extraulcount = themeextraul.length;
}
if((themeextraps !== undefined) || (themeextraul !== undefined)) {
var extratextpositions = {};
$.each(themeextraps, function(i, themeextraps) {
extratextpositions[themeextraps.position] = 'p';
})
$.each(themeextraul, function(i, themeextraul) {
extratextpositions[themeextraul.position] = 'ul';
})
$.each(extratextpositions, function(key, value) {
if(extratextpositions[key] == 'p') {
addExtraP.call(this);
} else {
addExtraUl.call(this);
}
});
$('#themelink').val(ui.item.themelink);
if(themelinkinclude == 1) {
$('#themelinkinclude').prop("checked", true);
} else {
$('#themelinkinclude').prop("checked", false);
}
event.preventDefault();
}
},
open: function(event, ui) {
$(".ui-autocomplete").css("z-index", 1000);
},
complete: function(){
$("#themename").removeClass("ui-autocomplete-loading");
}
}
});
I'm able to get the simple key:value values just fine, but I get undefined for the arrays. I'm sure there's a different way I need to pull those in, but I don't know how and can't seem to find the answer in other threads on here. Any help would be greatly appreciated!
Figured out a way to get around this problem, thanks to some help from #Bibberty. I'm not sure if this is the most graceful or easy way to solve it, but it worked for me. I created an array from the JSON data values, then created variables from the arrays within the data array and added them to the response return value. Here's the new functional code (or, at least, the part that matters):
//Autofill Theme Info based on text entry
$( "#themename" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "autotheme.php",
type: "GET",
dataType: "json",
data: {
q: request.term
},
success: function(data) {
const results = data.map(function (value, label) {
return [value];
})
var extraps = results[0][0]['extraps'];
var extraul = results[0][0]['extraul'];
response($.map(data, function(item) {
return {
id: item.id,
value: item.value,
label: item.label,
themename: item.themename,
themenotes: item.themenotes,
themedesc: item.themedesc,
themeimage: item.themeimage,
themeincludeextrap: item.themeincludeextrap,
themeincludeul: item.themeincludeul,
themelinkinclude: item.themelinkinclude,
themelink: item.themelink,
extraps: extraps,
extraul: extraul
}
}))
$("#themename").removeClass("ui-autocomplete-loading");
},
error: function(errorThrown){
console.log(errorThrown);
console.log("There is an error with theme autocomplete.");
}
});
},
minLength: 2,
select: function(event, ui) {
if (ui.item) {
$this = $(this);
console.log(ui.item.extraps);
$('#themeid').val('');
$('#extratext').html('');
$('#themename').val(ui.item.themename);
$('#themenotes').val(ui.item.themenotes);
$('#themedesc').val(ui.item.themedesc);
var themeimage = ui.item.themeimage;
var themeincludeextrap = ui.item.themeincludeextrap;
var themeincludeul = ui.item.themeincludeul;
var themelinkinclude = ui.item.themelinkinclude;
var themeextraps = ui.item.extraps;
var themeextraul = ui.item.extraul;
if(themeextraps !== undefined) {
var extrapcount = themeextraps.length;
}
if(themeextraul !== undefined) {
var extraulcount = themeextraul.length;
}
...

How can i put hidden id with autocomplete jquery

I want to put hidden id when get the value from autocomplete for add to database but now when i get value from autocomplete and add to database it's add value is label name not the id of the data
<input type='text' id='id' name='id' class='id_line' placeholder='Item Code'/>
This my jquery code
$("#add_line").on('click',function(){
$('.tbl_add_line').append(data);
$('.id_line').autocomplete({
source: function (request, response){
$.ajax({
url : "<?php echo site_url('warehouse/get_id');?>",
dataType: "jsonp",
data : {
q: request.term
},
success: function( data ) {
response(data);
}
});
},
});
i++;
});
And this is function to get data to show in autocomplete
function get_id(){
$result = "";
if(isset($_GET['q'])){
$code = $_GET['q'];
$this->db->like("item_code",$code)->select('*');
$this->db->order_by("item_code");
$result = $this->db->from("tbl_item_code")->get()->result();
}
$arr = array();
foreach($result as $key){
$arr[] = array(
'id' => $key->id,
'value' => $key->id,
'label' => $key->item_code."(".$key->id.")",
);
}
echo $_GET['callback']."(".json_encode($arr).")";
}
You can use _renderItem method to add custom attributes to created elements.
Try this:
$(function() {
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"
}];
$("#project").autocomplete({
minLength: 0,
source: projects,
focus: function(event, ui) {
$("#project").val(ui.item.label);
return false;
},
select: function(event, ui) {
$("#project").val(ui.item.label);
$("#project-id").val(ui.item.value);
$("#project-description").html(ui.item.desc);
return false;
}
})
.autocomplete("instance")._renderItem = function(ul, item) {
return $("<li>")
.append("<a>" + item.label + "<br>" + item.desc + "</a>")
.appendTo(ul);
};
});
#project-label {
display: block;
font-weight: bold;
margin-bottom: 1em;
}
#project-icon {
float: left;
height: 32px;
width: 32px;
}
#project-description {
margin: 0;
p
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<div id="project-label">
Select a project (type "j" for a start):</div>
<input id="project">
<input type="text" id="project-id" disabled>
<p id="project-description"></p>
Fiddle here

Datatable tr click function

I want to do some operations after clicking a particular row. I followed the API and this is what I ended up with but the click event is not working.
$(document).ready(function() {
table = $('#employees').dataTable( {
"bJQueryUI": true,
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "show_employee_processor.php",
"aoColumns": [
{ "sTitle": "Empoyee ID" },
{ "sTitle": "Last Name" },
{ "sTitle": "First Name" },
{ "sTitle": "BBan Number" },
]
} );
table.$('tr').click(function() {
var data = table.fnGetData( this );
alert(data);
});
} );
The datatable is getting drawn but the click event is not working. What am I missing?
try delegated event:
table.on('click','tr',function() {
var data = table.fnGetData( this );
alert(data);
});
or:
$('#employees').on('click','tr',function() {
var data = table.fnGetData( this );
alert(data);
});
$("#employees tr").click( function( e ) {
if ( $(this).hasClass('row_selected')==false ) {
table .$('tr.row_selected').removeClass('row_selected');
$(this).addClass('row_selected');
var data = table.fnGetData( this );
alert(data);
}
else{
$(this).removeClass('row_selected');
}
});
CSS>
#employees tr.row_selected{
background-color:#B5CCD2;
opacity:0.95;
font-weight:bold;
}

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