Question regarding jQuery UI autocomplete

Thanks myty.
Much cleaner!

No problem Pullo. :slight_smile:

For completion sake, the broken behavior you coded is clearly documented: http://api.jqueryui.com/autocomplete/#option-source

An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]

The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only value properties, the value will also be used as the label.

The problem was that using the arrow keys to navigate the autocomplete list means selecting the item too.

Hi myty,

Yup, I should have read that the docs in more depth first time round :slight_smile:
Anyway, I’ve been playing around with this and just realized that in addition to label and value properties you can also specify arbitrary other properties (as you have done in your second example with the data property).
That’s a neat trick. Thanks!

Well, that’s pretty much javascript 1on1. The source is an array, of strings or of objects.

We have the case of an array of objects.
A JS object can be freely augmented, and the order of properties in an object is not important.

Thus, adding properties and even methods to the objects in that array is anyone’s choice.

Hi Pullo,

what’s up?

I am about to try using the autocomplete with data fetched from a database. On the jQuery website I can’t really see how the PHP fetches the data. Looking on the Internet I found this website:

Is this more or less how the PHP and JavaScript should look like? Or what would you recommend?

Thank you in advance!

That looks like it should work; I did it before Christmas with the help of Pullo and below is the code we came up with. I wanted to use an external file for the data but for some reason it did not work.


<label for="title_A">Title A: </label>
<input type="text" name="title_A" id="title_A" /><br/>





<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
		$(function() {
			var availableTitles = [
			<?php
			$sql = "SELECT description FROM title ORDER BY description ASC ";
			$stmt = $PDO->query($sql);
			$performers = array();
			while ($title = $stmt->fetchColumn()) {
				$title = '"'.$title.'"';
				$titles[] = $title;
			}
			$titlelist = join(",".PHP_EOL, $titles);
			print_r($titlelist);
			?>
			]
			$("input[name^='title_'").autocomplete({
				source: availableTitles
			});
		});
		</script>

This code allowed for multiple autocompletes on a page but the project died and I did not go any further.

Hi Rubble,

thanks a lot for posting that code, will try it out.

I’m not that familiar with some of the syntax used in the PHP, but do you know if the value from the text input is sanitized? That is, safe to use in the query?

Thank you.

Cheers.

The php code creates an array of all the options in the database so the javascript only sees the array; the MySQL is server side and you can change the pdo code slightly to bind the values.
I did this for use by a single user on a local system and so the security was not very high and as I say the project died so I did not take it any further.

You can create a text file independently which would hold the array; you could do this securely and use the file in the javascript. There would be no php on the page then; I needed to do it this way as if the item the person was typing into the text input did not exist it was added to the database. This meant the array could change every time the page was visited.

I have had a bit of time today and so had a look into autocpmplete with a text file. Some sites said it could not be done but I found this code:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Autocomplete</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>
</head>
<body>

<h2>Using a text file</h2>
<div class="ui-widget">
  <label for="model">Model: </label>
  <input id="model">
</div>

<script>
$(function() {
$.get( "results.txt" ).done(function( data ) {
    $( "#model" ).autocomplete( { source: data.split( "\
" ) } );
});
});
</script>

</body>

</html>

The text file is in the format:
Ford
Nissan
Renault
Volvo

If your data is not changing very often and/or you are worried about security you could create a text file and use it instead of the php database call. You can still create the text file from the database contents but it could be in a more secure part of your website. If you have a form to upload data into the database you could just generate the text file at the same time as updating the database.

Hi Rubble,

If your data is not changing very often and/or you are worried about security you could create a text file and use it instead of the php database call. You can still create the text file from the database contents but it could be in a more secure part of your website. If you have a form to upload data into the database you could just generate the text file at the same time as updating the database.

I could try that as well, thanks for the tip. The query will probably be quicker as well, no?

I haven’t had an opportunity to test the autocomplete but will let you know once it’s working.

I would guess on a small text file it would be quicker but at some point a database method might get quicker?

If you are after speed you could always do a couple of speed tests.

I managed to get the autocomplete working but there’s a problem with the CSS. This is an issue I have dealt with before but whatever I did last time is not working now.

There is another jQuery ui widget on my webpage and the CSS styles for that plugin are being applied to the autocomplete which I don’t want. The autocomplete has it’s only style. On the jQuery ui website I downloaded the autocomplete and gave the CSS as scope which I named “a_com”. Looking at the downloaded file I see that the “a_com” class has been applied to most classes but not all of them.

This is the HTML for the autocomplete. Should I rename the class to something else? I probably gave the other plugin it’s own scope.

<div class="ui-widget">
<label for="tags">Find:</label>
<input id="auto"  />
</div>

If anyone has a solution, then please let me know.

Thanks, will investigate further.

Hey RedBishop,

I vaguely remember helping you out with this.
Wasn’t there a tool you used to make a custom, name-spaced build?

I vaguely remember helping you out with this.
Wasn’t there a tool you used to make a custom, name-spaced build?

You are probably referring to the CSS scope tool. Perhaps I’ll get it right.

Hi Pullo,

how are you doing? Good I hope!

Sorry to bother you with this but perhaps you will know how to adapt the jQuery Mobile autocomplete widget, so that the results can be turned into links.

This is what I’m currently using for the jQuery UI autocomplete:

$(function() {

$("#search").autocomplete({
    source: "search.php",
        select: function (event, ui) {
        event.preventDefault();
        $(this).val(ui.item.value);
        window.location.href = ui.item.data;
    },
    minLength: 2,
    messages: {
        noResults: '',
        results: function() {}
    }

});
});

Here is the link to the jQuery Mobile autocomplete where one can view the JavaScript: http://demos.jquerymobile.com/1.4.3/listview-autocomplete-remote/

I’ve tried a few things but all to no avail.

Thank you in advance!

Hi RedBishop,

All good here. With you too, I hope.

How do you mean “links”?

Do you mean that when you type something into the search field, you would like the results that the autocomplete widget returns to be displayed as links which you can then tap and be taken to another page?

Hi Pullo,

All good here. With you too, I hope.

I’m all right thanks.

How do you mean “links”?

Do you mean that when you type something into the search field, you would like the results that the autocomplete widget returns to be displayed as links which you can then tap and be taken to another page?

Yes, that’s what I’m trying to achieve. I’ve added the previous code

select: function (event, ui) {
        event.preventDefault();
        $(this).val(ui.item.value);
        window.location.href = ui.item.data;
    },

that you helped me with to the jQuery mobile autocomplete but that didn’t work. If only it was so simple.

Thank you for your assistance with this!! :slight_smile:

Hi,

It seems that you can attach a click handler to the listview like so:

$('#listview').on('click', 'li', function() {
  console.log("Element clicked: " + this);
});

Note the use of event delegation, as the individual <li> elements will not be present when the page is initially rendered.
I found that, here.

The example you linked to does this, to build the HTML:

.then( function ( response ) {
  $.each( response, function ( i, val ) {
    html += "<li>" + val + "</li>";
  });
  $ul.html( html );
  $ul.listview( "refresh" );
  $ul.trigger( "updatelayout");
});

In your code you could (for example) add a data attribute to the <li> elements which represents the page the user should be taken to:

html += "<li data-location=" + someVariableHoldingTheLocation + ">" + val + "</li>";

Then from within the event handler:

$('#listview').on('click', 'li', function() {
  window.location = this.getAttribute("data-location");
});

Hi Pullo,

please excuse my late reply. I did manage to get it working.

Thanks a lot for helping me out. Again!

Hope you are having a great week. Cheers.