Javascript 限制用户键入新名称,并仅允许从现有列表中进行选择

Javascript 限制用户键入新名称,并仅允许从现有列表中进行选择,javascript,html,angularjs,Javascript,Html,Angularjs,我正在研究angularjs的自动完成文本框功能。我只希望用户从现有的自动完成列表中选择名称,而不是键入新名称。例如,当用户键入'Al'自动完成列表显示匹配列表时,用户可以从现有列表中选择一个名称,而不是键入新名称。如何限制用户提交现有列表中不存在的新名称 演示: 代码示例: $scope.countryList = ["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua & Ba

我正在研究angularjs的自动完成文本框功能。我只希望用户从现有的自动完成列表中选择名称,而不是键入新名称。例如,当用户键入
'Al'
自动完成列表显示匹配列表时,用户可以从现有列表中选择一个名称,而不是键入新名称。如何限制用户提交现有列表中不存在的新名称

演示:

代码示例:

    $scope.countryList = ["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua & Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia & Herzegovina","Botswana","Brazil","British Virgin Islands","Brunei"];
$scope.validateField = function(){
  alert("Clicked on submit , validte field");
}
    $scope.complete=function(string){

        var output=[];
        angular.forEach($scope.countryList,function(country){
            if(country.toLowerCase().indexOf(string.toLowerCase())>=0){
                output.push(country);
            }
        });
        $scope.filterCountry=output;
    }
    $scope.fillTextbox=function(string){
        $scope.country=string;
        $scope.filterCountry=null;
    } 
任何输入都会有帮助。

您可以使用以下方法检查输入的有效性,并使用
ng change

    $scope.checkInput = function(){
        $scope.validInput = $scope.countryList.indexOf($scope.country) > -1;
    }

您可以禁用“提交”按钮,还可以高亮显示输入字段的红色边框,告诉用户从下拉列表中选择名称

首先,您需要更新
complete()
函数。使用
else if
语句检查值是否来自列表,如果不是,则可以在该
else if
语句中实现所需的逻辑

此方法灵活且易于自定义错误生成消息。您可以显示和隐藏包含错误消息的
div
,也可以使用
ng style
ng class
在输入字段上应用css
style
。现在我将向您展示如何禁用或启用按钮。以下是更新的代码段:

 $scope.complete = function(string) {

    var output = [];
    angular.forEach($scope.countryList, function(country) {
      if (country.toLowerCase().indexOf(string.toLowerCase()) >= 0) {
        output.push(country);
        $scope.enableDisable = false;
      } else if (country.toLowerCase().indexOf(string.toLowerCase()) < 0) {
        $scope.enableDisable = true;
      }
    });

    $scope.filterCountry = output;
  }
$scope.complete=函数(字符串){
var输出=[];
angular.forEach($scope.countryList,函数(国家){
if(country.toLowerCase().indexOf(string.toLowerCase())>=0){
输出推送(国家);
$scope.enableDisable=false;
}else if(country.toLowerCase().indexOf(string.toLowerCase())<0){
$scope.enableDisable=true;
}
});
$scope.filterCountry=输出;
}
在html部分,您只需要添加ng disabled属性并设置其值

 <input type="submit" value="submit" ng-disabled="enableDisable" ng-click="validateField()">

因此,您可以在
else if
语句中执行任何您想要的操作,以获取所需的错误消息