Typeahead.js 在远程 url 中包含动态变量

新手上路,请多包涵

我已经尝试了几个小时,在我的“远程”路径中获取一个变量。变量将根据另一个输入而改变。这是代码:

 school_value = $('#school').val();
$('#school').change(function () {
    school_value = $(this).val();
    $('#programme').typeahead('destroy'); // I have also tried with destroy - but it doesnt work.
});
$('#programme').typeahead({
    remote: 'typeahead.php?programme&type=1&school_name=' + school_value,
    cache: false,
    limit: 10
});

变量“school_type”未在远程地址中设置,因此未被调用。

你知道如何让它工作吗?我刚刚从 Bootstrap 2.3 切换到 3,然后注意到 typeahead 已被弃用。上面的代码适用于 Bootstrap 2.3,但似乎在初始化脚本时,远程路径被锁定。

原文由 FooBar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 410
2 个回答

我找到了解决方案!代码:

 $('#programme').typeahead({
    remote: {
        url: 'typeahead.php?programme&type=1&school_name=',
        replace: function () {
            var q = 'typeahead.php?programme&type=1&school_name=';
            if ($('#school').val()) {
                q += encodeURIComponent($('#school').val());
            }
            return q;
        }
    },
    cache: false,
    limit: 10
});

基于这个线程的答案: Bootstrap 3 typeahead.js - remote url attributes

请参阅 typeahead.js 文档 中的函数“replace”

原文由 FooBar 发布,翻译遵循 CC BY-SA 3.0 许可协议

我相信接受的答案现在已经过时了。 remote 选项不再有 replace 。相反,您应该使用 prepare

 $('#programme').typeahead({
    remote: {
        url: 'typeahead.php?programme&type=1&school_name=',
        prepare: function (query, settings) {
            settings.url += encodeURIComponent($('#school').val());

            return settings;
        }
    }
});

我遇到的一个问题是从另一个 typeahead 对象中提取值。 Typeahead 本质上是复制您的输入,包括所有类,因此您有两个几乎相同的对象,一个是 tt-hint 类,另一个是 tt-input 。我必须指定它是 tt-input 选择器,否则我得到的值是一个空字符串。

 $('.field-make').val();  // was "" even though the field had a value
$('.field-make.tt-input').val();  // gave the correct value

Bloodhound 远程选项

原文由 andrewtweber 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题