Introduction
We already have a lot of controls which use AjaxToolkit or JQuery UI Combobox or AutoComplete Textboxes from different 3rd party controls. But, if we have a limitation of not using these above mentioned controls, then I suppose we would be in a state of confusion about achieving our targets. This was the exact situation I got from one of our CodeProject member.
Background
The basic idea of this is to get the list of data that the auto complete textbox is supposed to get it from the database by using ADO.NET or LINQ or your normally preferred DB call on the page load, for the first time itself. And, now save it to a hidden variable and play with it as per our requirements.
Using the Code
Let's go through my example here.
This is the HTML content first.
// Hidden source. Provide the JSON data on the page load for the first time,
// I've taken some example data.
<input type='hidden' value='{"100":one,"200":two,"300":
three,"400":four,"500":our}' id='hdnVal'/>
// Auto complete Text box
<input type='text' id='txtEnter' /><br />
// Hidden DIV and Select control to update whenever a key is entered into the textbox
<div id='divAreaHolder' style='display:none; border: black 0px solid;
heigth:30px; width: 200px; overflow-y:auto;'>
<select id='sltOptions'></select>
</div>
This is simple HTML code which contains:
input (type=hidden)
to hold the data, input
textbox for us to enter a text and Dropdownlist
which holds the relevant data that matches the user entered text
The below jQuery code takes the data entered into the textbox and will call the GetAutoHelp
method.
var arrData;
$('#txtEnter').keyup(function () {
$('#sltOptions').find('option').remove().end();
if ($(this).val() === '') {
$('#divAreaHolder').hide();
return false;
} else {
arrData = $('#hdnVal').val().replace('{', '').replace('}', '').split(",");
GetAutoHelp($(this).val());
}
});
The below function is to do the manipulation on the hidden data source to get the options that are similar to the text entered into the Autocomplete textbox.
function GetAutoHelp(txt) {
var flag = 0;
var $opn;
$('#divAreaHolder').show();
$opn = new Option('--Select--', '0');
$('#sltOptions').append($opn);
$(arrData).each(function () {
if (this.contains(txt)) {
$opn = new Option($.trim(this).split(':')[1], $.trim(this).split(':')[0]);
$('#sltOptions').append($opn);
flag = 1;
}
});
if (flag === 0) {
$('#sltOptions').find('option').remove().end();
$opn = new Option('--No Options--', '0');
$('#sltOptions').append($opn);
}
}
The below jQuery code is to set the selected option's value into the auto complete textbox when selected from the Dropdownlist
's option.
$("select").change(function () {
if ($('select option:selected').val() === 0) return;
else $('#txtEnter').val($('select option:selected').text());
});
Limitations: If the data list is too big/high, then the server might take some time to load the page.
Hope this helps you all.
Thank you.