How to set AutoCompleteExtender to allow only values from autocompletion list?
Does anybody know how using AutoCompleteExtender (from AJAX Contro开发者_StackOverflowl Toolkit) prevent user from entering anything not in suggested values?
First, check if you would rather use the new AjaxToolKit ComboBox.
If you can't (for example, if you're using .NET Framework 2.0), you can manipulate the AutoComplete to answer your demands but it's a headache and not really what the control was made to.
The checks are supposed to be made inside the javascript, you add an event to catch OnItemSelected.
And then create a function:
function OnItemSelected (sender, e)
{
-- validate here
}
Another option is to require user to choose value from list by manipulating the events:
onchange, onclick & onblur. But it takes some time to find just right combination.
To lift your spirits I'll tell you that it is possible (we've done it, but I can't attach our code because of copyright issues).
Something like this can help you
Javascript
<script type="text/javascript">
var isItemSelected = false;
//Handler for AutoCompleter OnClientItemSelected event
function onItemSelected() {
isItemSelected = true;
}
//Handler for textbox blur event
function checkItemSelected(txtInput) {
if (!isItemSelected) {
alert("Only choose items from the list");
txtInput.focus();
}
}
</script>
ASPX
<asp:Button onblur="checkItemSelected(this)" ../>
<ajax:AutoCompleteExtender OnClientItemSelected="onItemSelected" ../>
The previously submitted answer using a boolean isItemSelected
will fail to work if a user initially selects an item from the list, and then goes back and decides to type a value instead.
In order to prevent this, there should also be an event that resets isItemSelected to false when the input comes to focus:
ASPX
<asp:TextBox onblur="checkItemSelected(this)" onfocus="resetItemSelected()"../>
JS
function resetItemSelected() {
isItemSelected = false;
}
Or...
Use a JS event that is triggered on select, and copy the value from the textbox to a hidden field. Then use the value from the hidden field for processing.
ASPX
<asp:HiddenField runat="server" ID="hf1"/>
<asp:TextBox runat="server" ID="tb1"></asp:TextBox>
<ajax:AutoCompleteExtender ID="ace1" runat="server" TargetControlID="tb1" OnClientItemSelected="userSelected" .../>
JS
function userSelected(sender, e) {
var selectedItem = e.get_value();
$get("<%= hf1.ClientID%>").value = selectedItem;
return false;
}
But wait... there's more!
To enhance the above, you can add a blur event to the textbox that validates whether or not the textbox value matches the value in the hidden field, and clears the textbox when the value does not match.
//remove value if not selected from drop down list
$('#<%=tb1.ClientID%>').blur(function () {
if ($('#<%=hf1.ClientID%>').val() !== $(this).val()) {
$(this).val("");
//optionally add a message near the input
}
});
This will make it obvious to the user that the input is not being accepted.
精彩评论