How to use Lift’s Auto Complete functionality optionally


Auto Complete functionality enables users to quickly find and select from a pre-populated list of values as they type, leveraging searching and filtering.

We can see live example in Google. Whenever we type something for searching, Google provides us some suggestions. This increases the speed of our work.

This functionality is used in 2 forms :
1. Only auto complete is allowed. i.e. We can select only from pre-populated list. We can not enter our own text.
2. Auto Complete as optional i.e. Either we can select from pre-populated list or we can type our own text.

So here I am explaining 2nd feature : Auto Complete with optional

1. Add below line in Boot.Scala

import net.liftweb.widgets.autocomplete.AutoComplete
  class Boot {
    def boot {
      ...
      AutoComplete.init
      ...
    }
  }

2. In order to implement in Snippet , follow below lines :-

"#autocomplete" #>AutoComplete(startValue,
                               getResults _, 
                                value => takeAction(value)
                                , List(("minChars" -> "3"))
/**
where:
startValue is a string for the initial value of the AutoComplete text field.
getResults is a function to populate the Autocomplete drop down results.
takeAction is a function called when the form is submitted, containing the value of the widget
**/
def getResults(current: String, limit: Int): Seq[String] = {
...
}
 /**
where
current is the string typed into the autoComplete text field.
limit is an integer to limit the number of Strings returned by the function
**/
def takeAction(str : String) = {
println("Selected Value"+str)
}

Till now, only populated values can be selected.
3. To make this functionality optional, just add below code :

$(document).ready(function() {
		$('span#autocomplete input').bind('blur', function() {
			$(this).next().val($(this).val());
		});
	});

Auto complete changes id of text box therefore I use “span#autocomplete input” as id to approach that text box.

Now whether select values from populated list or enter your own value, you can access that value in takeAction() method.

About Rishi Khandelwal

Software Consultant at Knoldus Software LLP, New Delhi, India having around 2.5 years industry experience. He has working experience in various technologies such as Scala, Java, Play, Akka, Lift Web, Backbone.js, javascript, Jquery, Amazon EC2, WebRTC,
This entry was posted in Web. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s