Twitter typeahead javascript library is a fast and fully-featured autocomplete library inspired by the autocomplete search functionality from twitter.
Following script is HTML code for defining input with typeahead. Note there is one
data-provide="typeahead" defined within the input node. This attribute notifies the plugin that we are going to perform a lookup with this textbox.
<div class="col-md-3 col-xs-6">
<label for="StudentID" class="control-label">Enter Student ID</label>
<div id="details"></div>
<div class="input-group input-group-sm">
<input type="text" name="studentId" id="studentId" class="form-control input-sm" data-provide="typeahead">
</div>
</div>
Javascript part:
$("#studentId").typeahead({ minLength: 4, source: function (query, process) { var students = []; map = {}; // This is going to make an HTTP post request to the controller return $.post('/Student/StudentLookup', {studentId: query}, function (data) { // Loop through and push to the array $.each(data, function (i, student) { map[student.Name] = student; students.push(student.Name); }); // Process the details process(students); }); }, updater: function (item) { var studentId = map[item].StudentId; // Set the text to our selected id $("#details").text("Selected : " + studentId); return item; } });
Controller Part:
public class StudentController : Controller { public ActionResult StudentLookup() { var students = new List<StudentEntity> { new StudentEntity {StudentId = "01", Name = "Frank Zhang"}, new StudentEntity {StudentId = "02", Name = "Andrew Chen"}, new StudentEntity {StudentId = "03", Name = "John Smith"}, new StudentEntity {StudentId = "03", Name = "Johnson Stone"}, }; return Json(students, JsonRequestBehavior.AllowGet); } }Reference:
https://github.com/bassjobsen/Bootstrap-3-Typeahead
http://www.deanhume.com/Home/BlogPost/twitter-bootstrap-typeahead-and-asp-net-mvc---key-value-pairs/88
No comments:
Post a Comment