Hi Guys,

 

In this post i am going to talk about how we could create an auto complete text box in HTML5 using DataList. Also we will see how we could use knockout to bind an observable array to the auto complete list. Then we will populate the data depending upon the selection of a user.

The first thing that we need to do is add a Scripts folder and then download the knockout.js into that folder. Then we will include the knockout.js script file into our html page.

[hr]

<html>
<head>
<title>HTML 5 Datalist Knockout Auto Complete Text Box</title>
</head>

<body>
<script type=”text/javascript” src=”Scripts/knockout-2.2.1.js” ></script>

</body>

</html>

[hr]

Now just below the script tag add another script tag. In this script tag we will define our view model with which we will bind our html view.

[hr]

<script type=”text/javascript” >
function userViewModel () {
this.users = ko.observableArray();
this.username = ko.observable(”);

this.users.push(“Abhishek Shukla”); this.users.push(“user 1”); this.users.push(“user 11”);
this.users.push(“user 2”); this.users.push(“user 22″);

this.currentUser = {
firstName: ko.observable(”),
lastName: ko.observable(”),
address: ko.observable(”)
};

this.setUser = function () {
if (this.username() !== ”) {
this.setCurrentUser(this.username());
}
}.bind(this);

this.setCurrentUser = function (username) {
var userFullName = username.split(‘ ‘);
this.currentUser.firstName(userFullName[0]);
this.currentUser.lastName(userFullName[1]);
this.currentUser.address(“Gurgaon, India”);
}.bind(this);
};
ko.applyBindings(new userViewModel());
</script>

[hr]

Now that our ViewModel is ready we will create a view and bind it to the ViewModel properties and events.

<p>Type User Name :
<input list=”Employees1″ data-bind=”value: username, onchange: setUser()” type=”text” />
<datalist id=”Employees1″ data-bind=”foreach: users”>
<option data-bind=”text: $data”></option>
</datalist>
</p>
<p>First Name : <span data-bind=”text: currentUser.firstName” /></p>
<p>Last Name : <span data-bind=”text: currentUser.lastName” /> </p>
<p>Address : <span data-bind=”text: currentUser.address” /> </p>

[hr]

Any questions, comments, feedback are most welcome.

The complete source code can downloaded from here.