【问题标题】:Bootstrap 3 typeahead.js - set form valBootstrap 3 typeahead.js - 设置表单 val
【发布时间】:2014-09-23 11:48:46
【问题描述】:

我正在将 typeahead.js 与 Bootstrap 3 一起使用,并且使用下面的代码似乎运行良好,以至于我可以从 json 文件中获得带有 countryName 值的下拉列表,但我现在想分配 @987654322 @ 到输入值属性,这样我就可以提交正确的countryID 而不是显示的文本。

我的json文件返回如下数据[{"ID": 1, "countryName": "United States"},{"ID": 2, "countryName": "United Kingdom"},{"ID": 3, "countryName": "United Emirettes"}]

var substringMatcher = function(strs) {
    return function findMatches(q, cb) {
    var matches, substrRegex;
    matches = [];
    substrRegex = new RegExp(q, 'i');
    $.each(strs, function(i, str) {
        console.log(str['countryName'])
      if (substrRegex.test(str['countryName'])) {
        matches.push({ value: str['countryName'] });
      }
    });
    cb(matches);
  };
};

$.getJSON("countries2.json",function(result){
   format: "json"
})
.done(function( data ) {
    $('#the-basics .typeahead').typeahead({
      hint: true,
      highlight: true,
      minLength: 2
    },
    {
      name: 'countries',
      valueKey: 'countryName',
      displayKey: 'value',
      source: substringMatcher(data)
    });
});

【问题讨论】:

    标签: jquery twitter-bootstrap-3 typeahead.js


    【解决方案1】:

    我想如果你改变你的 subStringMatcher 让它也给出国家 ID。在对象中添加带有值 ID 的键。试试这个:

    var substringMatcher = function(strs) {
        return function findMatches(q, cb) {
        var matches, substrRegex;
        matches = [];
        substrRegex = new RegExp(q, 'i');
        $.each(strs, function(i, str) {
            console.log(str['countryName'])
          if (substrRegex.test(str['countryName'])) {
            matches.push({ key:str['ID'], value: str['countryName'] });
          }
        });
        cb(matches);
      };
    };
    

    然后将 typeahead 选项 valueKey 更改为 key。

     $('#the-basics .typeahead').typeahead({
    
      hint: true,
      highlight: true,
      minLength: 2
    },
    {
      name: 'countries',
      valueKey: 'key',
      displayKey: 'value',
      source: substringMatcher(data)
    });
    

    【讨论】:

    • 您好,感谢您的回答。我现在可以看到输入到 typehead 函数的 ID,但是当我提交表单时,发送的值仍然是 countryName。看来 valueKey 没有做任何事情
    猜你喜欢
    • 2013-08-21
    • 1970-01-01
    • 2016-08-20
    • 1970-01-01
    • 2013-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    相关资源
    最近更新 更多