Need some help?

I'm usually available for small jobs or problem solving with jQuery or css, at reasonable rates. Just get in touch.

Web Hosting

We recommend Clook for web hosting. UK based, great service and great value.

Vertical slider with integrated autocomplete – jQuery UI

In response to a comment on my vertical slider with jquery ui demo page, here I’ve extended this further to integrate an autocomplete function.

I’ve envisaged a scenario where the slider is used to display a number of products (probably retrieved from a database), displayed within the slider as a photograph and a text description. With a large number of products it would be useful to add a “quickfind” option to allow the user to type in a search term, and then use autocomplete to match the entered term against values in the database. If the user selects a match, then the slider scrolls to that entry.

This is built on the standard code here, and can be used with or without the mousewheel extension. Here’s the javascript:

$("#quickfind").autocomplete({
    source: "get_descriptions.php",
    minLength: 2,//search after two characters
    select: function(event,ui){
        position = $(".scroll-content-item:contains("+ui.item.value+")").position();//search for a div containing the selected description and read its position
		
        var topValue = -(position.top);//content top is just the negative of the top position
		
	if (topValue>0) topValue = 0;//stop the content scrolling down too much
	if (Math.abs(topValue)>difference) topValue = (-1)*difference;//stop the content scrolling up too much

	sliderVal = (100+(topValue*100/difference));//calculate the slider position from the content position
	$("#slider-vertical").slider("value", sliderVal);//set the slider position
	}
});

You’ll see this is quite similar to the code used for the mousewheel, except in this case we’re initially calculating the position of the scroll pane and then the position of the slider. I’m using the jQuery contains() selector to find the div within the scroll pane which contains the selected text, and then the jQuery position() method to find how far down I need to scroll.

That’s the javascript, now let’s have a look at the php code:

//assumimg a $mysqli connection exists...

$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends

$qstring = "SELECT description as value,id FROM test WHERE description LIKE '%".$term."%'";
$result = $mysqli->query($qstring);//query the database for entries containing the term

if ($result->num_rows>0)
	{
	while($row = $result->fetch_array())//loop through the retrieved values
		{
				$row['value']=htmlentities(stripslashes($row['value']));
				$row['id']=(int)$row['id'];
				$row_set[] = $row;//build an array
		}
	echo json_encode($row_set);//format the array into json data
	}
else echo "error";

This is fairly straightforward – a couple of points worth mentioning. jQuery autocomplete sends the entered search term as a GET (get_descriptions.php?term=[searchterm]) so that’s what we need to retrieve to use. Autocomplete expects “value” for the text, so I’m retrieving the description field in my database as this.

And that’s about it. There’s a separate demo page here. Possible enhancement might be to provide a visual highlight – change the background colour or border colour – on the scroll just to make it more obvious.

Changelog

5 March 2012 – simplified javascript

Removed directly changing the top value of .scroll-content since this is done automatically by the slider

11 November 2010 – change to php code

Added error handling to the php code in the event that no match is found on search. This error did not affect users but caused a javascript error.

4 September 2010 – styling

added styling to the autocomplete/dropdown values and to the mouse, in order to make it more obvious that the autocomplete values are clickable.

12 responses to “Vertical slider with integrated autocomplete – jQuery UI”

  1. Simon says:

    jQuery UI autocomplete won’t do this, as far as I understand your question. You’d have to write some custom code to retrieve data into different fields.

  2. alfredo says:

    and what about only value…think you have a database with a lot of date and you must print the data in different input how i can whit an autocomplete about for example campany name and print all other data about this company in the other input

  3. Simon says:

    The files can go in any folder you want – it will depend on how your website is built as to where you put them.

  4. Sagarika Rayudu says:

    So the php files would go into which folder? views folder or public or routes?Also should we add anything to app.js or package.json?

  5. Simon says:

    The javascript stuff would be in the view, the get_descriptions.php which queries the database would be split between controller and model in an mvc set up.

  6. hii i got some problem,
    the code is works, but i have website with CI framework and i do not quite understand about mvc…

    could u tell me what code is in model or controller … .

    thanks before

  7. Simon says:

    Tony

    I don’t sorry.

  8. Tony says:

    Hi there, do you know a way to make touch events enabled inside the autocomplete?
    Cause i wanted to at least make possible to slide up and down the list with ipad 2.

  9. Simon says:

    Mostly, but you shouldn’t need to change the sliderVal settings – highlighted in your post – these are percentages and hence stay the same regardless of the height of the scrolling div. That 562 should be 100.

  10. Zelf says:

    So to still use your select scroll feature would this look correct then?

    $("#search_query").autocomplete({
    		source: function( request, response ) {
    			$.ajax({
    				url: "http://localhost/site/controller/",
    				type: "post",
    				dataType: "json",
    				data: {
    				term: request.term
    				},
    				success: function(data) {
    					response(data);
    				}
    			});
    		},
    		minLength: 2, //search after two characters
    		select: function(event,ui){
    		    position = $(".scroll-content-item:contains("+ui.item.value+")").position();//search for a div containing the selected description and read its position
    
    		    var topValue = -(position.top);//content top is just the negative of the top position
    
    			if (topValue>0) topValue = 0;//stop the content scrolling down too much
    			if (Math.abs(topValue)>difference) topValue = (-1)*difference;//stop the content scrolling up too much
    
    			$("#scroll-content").css({top:topValue});//set the new content top
    
    			sliderVal = (562+(topValue*562/difference));//calculate the slider position from the content position
    			$("#slider-vertical").slider("value", sliderVal);//set the slider position
    		}
    	});
  11. Simon says:

    Hi Zelf

    Yes, although the default Autocomplete method is GET, you can do this using the Autocomplete callback variation and explicitly define an AJAX POST. Replace the source option above with something like:

    source: function( request, response ) {
         $.ajax({
         url: "get_descriptions.php",
         type: "post",
         dataType: "json",
         data: {
                term: request.term
                    },
         success: function(data) {
                response(data);
                    }
          });
    }

    (Obviously you’d change the target file to expect POST data as well.)

  12. Zelf says:

    Is it possible to submit the autocomplete with the query term as a POST rather than a GET?

Useful? Interesting? Leave me a comment

I've yet to find a way of allowing code snippets to be pasted into Wordpress comments - so if you're trying to do this you'd be better off using the contact form.