JQuery autocomplete - Display multiple values - javascript

I want to display multiple values to the autocomplete box.
In my understanding JQuery autocomplete uses the key "value" as default to display text to the box.
But I want to display the keys "value", "company" and "tags" which I get by the search result.
Here is what I have:
My Database query - Here only 'value'=>$product->title gets used.
public function autoComplete(Request $request) {
$query = $request->get('term','');
$products = Products::where('title', 'LIKE', '%' . $query . '%')
->orWhere('company', 'LIKE', '%'. $query .'%')
->orWhere('tags', 'LIKE', '%'. $query .'%')
->get();
$data=array();
foreach ($products as $product) {
$data[]=array('id'=>$product->id,
'value'=>$product->title,
'company'=>$product->company,
'tags'=>$product->tags);
}
if(count($data))
return $data;
else
return ['value'=>'No Result Found','id'=>''];
}
My JQuery autocomplete Script
<script>
$(function()
{
$( "#search_text" ).autocomplete({
source: "{{ route('searchajax') }}",
minLength: 1,
select: function(event, ui) {
$('#search_text').val(ui.item.value);
},
open : function(){
$(".ui-autocomplete:visible").css({top:"+=13"});
},
});
});
My Input Field
<div class="col">
<input class="form-control form-control-lg form-control-borderless ui-autocomplete-input"
id="search_text"
type="search"
name="q"
value="{{ isset($s) ? $s : '' }}"
placeholder="Search for Titles, Companys or Tags"
autocomplete="off" />
If it helps, I use Laravel for this project.

would it not be easiest to manipulate the 'value' field server side to get the desired result? for example like this
'value'=>$product->title.', '.$product->company.', '.$product->tags);

I found the solution myself with help of the
JQueryUI Documentation
I had to manipulate the renderItem() extension point.
This is my script now, work perfectly fine:
<script>
$(function()
{
$( "#search_text" ).autocomplete({
source: "{{ route('searchajax') }}",
minLength: 1,
select: function(event, ui) {
$('#search_text').val(ui.item.value);
return false;
},
open : function(){
$(".ui-autocomplete:visible").css({top:"+=13"});
},
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div><strong>" + item.value + "</strong><br>" + item.company + "</div>" )
.appendTo( ul );
};
});

Related

jquery autocomplete input field nothing happens

I want to implement one autocomplete input field but when I start to insert some text nothing happens, for one sec the "busy circle" shows up and that is all.
Here is my code:
html>
<div class="products-inv"><?php echo $product_name ?></div>
<input type="text" id="product_name" name="product_name" />
the first div is test for displaying the php variable value what shows up well
jquery>
jQuery( function() {
function log( message ) {
jQuery( "<div>" ).text( message ).prependTo( "#log" );
jQuery( "#log" ).scrollTop( 0 );
}
jQuery( "#product_name" ).autocomplete({
source: "../route/to/search.php",
minLength: 2,
select: function( event, ui ) {
log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
});
} );
and the search.php file content>
$query = 'database data';
$db->setQuery( $query );
$product_name = $db->loadResult();
the error console is empty.
thanks in advice
your server side code does not return the data expected by the plugin.
From the documentations of the jQuery autocomplete plugin about the source option
When a string is used, the Autocomplete plugin expects that string to
point to a URL resource that will return JSON data
your search.php script must return the items you want to suggest to the user (show up in the autocomplete list )
that is an example:
/*term is a parameter generated by the plugin and contains
the string the user has typed in the input*/
$_GET['term'] = isset($_GET['term']) ? $_GET['term'] : null;
//manage your own query depending on your database and preferred way for db interactions
//$query = "select product_name from product where product_name like ?";
//$term = "%{$_GET['term']}%";
//$stmt = $mysqli->prepare($query);
//$stmt->bind_param("s", $term);
//$stmt->execute();
//$result = $stmt->get_result();
$autocompleteList = [];
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$autocompleteList[] = $row['product_name'];
}
die(json_encode($autocompleteList));

Jquery Autocomplete and MySQL ID Value

hoping someone can help me out with something.
I've got a piece of code which allows the Jquery Autocomplete. What I'm wanting to do is to use the ID(primary key) from my MySQL table and then use that to POST on to another screen.
How would I go about getting the ID into a hidden value from the Jquery code?
Here are my snippets.
Jquery
<script>
$(function() {
$( "#skills" ).autocomplete({
source: 'JQUERYTEST.php'
});
});
</script>
Html
<div class="ui-widget">
<label for="shop">Shopname: </label>
<input id="shop">
</div>
Php/MySQL
<?php
//database configuration
$dbHost = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'aurora';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query = $db->query("SELECT * FROM shops WHERE shopname LIKE '%".$searchTerm."%'");
while ($row = $query->fetch_assoc()) {
$data[] = $row['shopname'] . ' - '. $row['streetaddress'] . ' - ' . $row['postcode'];
}
//return json data
echo json_encode($data);
?>
Thanks!
Firstly, you will have to use an Ajax call to get the data from the server. So, change your autocomplete function and add an ajax call to receive a response. Then you will have to loop the JSON array in jquery. I have created the id as the whole string with shopname, streetaddress and postcode. Currently, your code doesn't inserts the ID parameter from the database. You can create an id depending on your needs. Then dynamically I have created the HTML and then placed it inside the <div class="ui-widget">
<script>
$( function() {
$( "#skills" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "search.php",
dataType: "jsonp",
data: {
term: request.term
},
success: function( data ) {
var html = "";
$.each(data, function(i, item) {
var arr = item.split('-');
html += "<label for='shop'>Shopname:"+arr[0]+" </label><input id='"+item+"' type='hidden'><br>";
});​
$('.ui-widget').html(html);
}
});
}
});
});
</script>
Try this out. I hope this helps you.

Is there a way to hide autocomplete arrays from HTML source?

I have a JQuery autocomplete function going, fed by a json_encoded PHP array. Everything is functioning, but when I right click on the site to view the page source, I can see the entire array. What is this array contained sensitive information? Is there a better way to organize this code, making it more private with the same level of functionality?
On the main PHP/HTML page:
<?php include 'autocomplete.php'; ?>
which includes:
<?php
// connect to db
//fetch first and last name
$sql="SELECT first, last FROM names";
$result = mysqli_query($web_dbi, $sql) or die("Error " . mysqli_error($web_dbi));
while ($f=mysqli_fetch_array($result)) {
$names[] = array(
'label' => $f['first'] . " " . $f['last'];
);
}
echo json_encode($names);
?>
back on the main PHP/HTML page I have some JQuery:
... (JQuery CDNs)
<script type="text/javascript">
$(function() {
$( "#inputfield" ).autocomplete({
source: "autocomplete.php",
minLength: 1,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
</script>
The main issue is that in the source of the HTML page, this is visible:
$(function() {
var autocompletevalues = ["name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name","name"];
$( "#inputfield" ).autocomplete({
dataType: "json",
source: availableTags
});
});
It has to be like this:
$( "#birds" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
Ref: JQuery Autocomplete
search.php has to ftech json values which can then be displayed as a part of autocomplete.
Refer to this Fiddle: http://jsfiddle.net/handtrix/32Bck/
Update 1:
while($product_search->fetch())
{
$data[] = array(
'label' => trim($product_code)
);
}
echo json_encode($data);
JS Code:
$("#inputfield").autocomplete({
source:'search.php',
minLength:4
});

Jquery autocomplete source php function

I would like to attach a php function as a source for my autocomplete functionality, The problem is I am not getting any results back.
PHP function
function getUser(){
$users = R::findAll('users');
foreach ($users as $user) {
echo '<option value="'. $user->name .'" ';
if($_POST['filterUser'] == $user->name){
echo "selected";
}
echo $user->name . '</option>';
}
}
Auto completion
$( "#enterUser" ).autocomplete({
source:'test.php?str=' + $('filterUser').val(),
messages:
{
noResults: '',
results: function() {}
},
select: function( event, ui )
{
var selectedObj = ui.item;
},
autoFocus: true
});
});
In the autocomplete declaration, your source property must be the name of your php file (with some parameters).
Example:
source: 'your_php_file.php?str=' + $('filterUser').val()
In the PHP you must call the function you want to reach, and be sure that it echoes the appropriate JSON string.

Require that the input is in the datalist

I have an form input of type datalist, in this list is about 5000 options, because of the large amount of options a select form just is not practical as you are allowed to type and it suggests what you want with a datalist.
<div class='form-row'>
<div class='col-xs-12 form-group required' style="margin-top: -2px; margin-bottom: 0px;">
<h2><label class='control-label' style="font-size: 20px;">Product code</label></h2>
<input required id="ItemSelect" list=jobs style='font-size:21px;height: 40px;'
class='form-control'
name="Code">
<datalist id=jobs>
<?php
foreach ($this->Products as $a) {
$inputValue = " " . htmlentities($a["Code"] . " | " . $a["Name"]) . " ";
echo '<option>' . $inputValue;
}
?>
</datalist>
</div>
This is what i have now, however the user can type and submit things that are not in the list and i can not allow this. How can i stop this from happening?
Alert the user if the field has a incorect value
$('input[type="submit"]').on('click',function(e) {
$datalistval= $('#ItemSelect').val();
if ($('option[value="'+$datalistval+'"]').length == 0) //if no option is found alert the user
{
alert('incorect datalist value');
e.preventDefault();
}
});
jsfiddle: https://jsfiddle.net/ev63ghwk/
If you're willing to use jQuery UI's autocomplete this would work:
<?php // tweak the below to use your data
$arr = array( array('Name' => 'one'), array('Name' => 'two'), array('Name' => 'three') );
$optsArr = array();
foreach ($arr as $a) {
array_push( $optsArr , '"'.htmlentities( $a["Name"] ).'"' ); ;
}
$options = implode(",", $optsArr)
?>
var availableTags = [<?php echo $options ?>];
$(function() {
$( "#ItemSelect" ).autocomplete({
source: availableTags,
change: function (event, ui) {
if(!ui.item){
//http://api.jqueryui.com/autocomplete/#event-change -
// ui.item property is null if the input was not found in the list
$("#ItemSelect").val("");
}
}
});
});
Here's a working Demo

Categories