Monday, May 27, 2013

Autocomplete textbox using HTML5

Autocomplete textbox can be implemented in several ways as i had discussed also in earlier posts, but HTML 5 have some inbuild feature by which we can implement autocomplete feature for textbox quite easily. The most likely thing for me about HTML 5 is, its several inhancement in basic HTML input controls like <b>list</b> property of textbox.
Autocomplete textbox
There are several other also, like addition of new tags like <b>datalist</b>. We'll create autocomplete textbox using these two new additions only. But before starting the actual business, lets setup our environment first:
1) We can use visual studio 2010 with service pack 1. Without sp1, visual studio 2010 doesn't have HTML 5.
2) After sp1 we'll need to go to Tool Menu -> Option -> TextEditor -> HTML TAB -> Validation -> Select HTML 5 from Target dropdown.


  1. <input list="Employees" type="text" />
  2. <datalist id="Employees">
  3. <option value="Adarsh"></option>
  4. <option value="Madhukar"></option>
  5. <option value="Amar"></option>
  6. <option value="Avinash"></option>
  7. <option value="Kundan"></option>
  8. <option value="Amit"></option>
  9. <option value="Viresh"></option>
  10. <option value="Vivek"></option>
  11. </datalist>

You can bind it through database also:
Create HTML like:
  1. <input list="lstEmployees" type="text" id="Employee" runat="server" />
  2. <datalist id="lstEmployees" runat="server"></datalist>

and in code behind
  1. protected void Page_Load(object sender, EventArgs e)
  2. {
  3. if (!IsPostBack)
  4. bindListEmployee();
  5. }
  6. private void bindListEmployee()
  7. {
  8. using (Model.ModelContainer context = new Model.ModelContainer())
  9. {
  10. var q = from c in context.Employees
  11. select new {c.Id, Employee = c.EmployeeName + " "+ c.Designation };
  12. foreach (var item in q)
  13. {
  14. lstEmployees.InnerHtml += "<option value='"+ item.Employee +"'>";
  15. }
  16. }
  17. }

But there is one limitation to this approach, many browsers doesn't support HTML5.

No comments:

Post a Comment