jquery - 多个自动完成功能不起作用

标签 jquery jquery-ui codeigniter autocomplete jquery-ui-autocomplete

$(function() {
    function split( val ) {
        return val.split( /,\s*/ );
    }
    function extractLast( term ) {
        return split( term ).pop();
    }
    $( "#names" ).autocomplete({
        source: function(request, response) {
            $.ajax({ url: "<?php echo site_url('update/suggestions'); ?>",
            data: { term: extractLast( request.term )},
            dataType: "json",
            type: "POST",
            success: function(data){
                response(data);
            },
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            select: function( event, ui ) {
                var terms = split( this.value );
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push( ui.item.value );
                // add placeholder to get the comma-and-space at the end
                terms.push( "" );
                this.value = terms.join( "," );
                return false;
            }
        });
    },
    minLength: 2
    });
});

上面的代码替换现有的选择,而不是将新的选择添加到现有的选择中。这是在 Codeigniter 中。单个自动完成功能运行良好。 这不适用于多个输入字段,而是用于将多个值添加到单个输入字段。

最佳答案

您的代码有几个问题:

  • 您没有正确关闭$.ajax函数和source选项函数。
  • minLength: 2 也放错了位置。
  • 由于之前的问题,您的右括号/括号过多。

例如你有:

    source: function(request, response) {
        $.ajax({ url: "<?php echo site_url('update/suggestions'); ?>",
        ...
        success: function(data){
            response(data);
        },
    // missing closings
    focus: function() {

应该是:

    source: function(request, response) {
        $.ajax({
            url: "<?php echo site_url('update/suggestions'); ?>",
            ...
            success: function(data) {
                response(data);
            }
        });   // closes $.ajax function
    },    // closes the 'source' function
    focus: function() {


检查这个DEMO 具有正确的语法。它工作正常(我已向 ajax 添加了一个错误处理程序以显示一些静态结果)。

关于jquery - 多个自动完成功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8975312/

相关文章:

javascript - 比较设置 div 的 bgcolor 的值

JQuery Mobile UI DatePicker 定义日期格式

当内容禁用空白换行时,jquery-ui 对话框的大小不正确

jquery - Uncaught Error : cannot call methods on dialog prior to initialization; attempted to call method 'option'

php - 使用codeigniter和jquery插入后如何获取最后插入的ID

php - 在 null 上调用成员函数 helper()

javascript - 使用 Jquery 进行表单验证的行为不符合预期

php - 如何使用 jQuery 或 PHP 制作网页输出 XML?

php - 动态表单——设置数据库的正确方法?

javascript - 如何通过 javascript/AJAX 使用 reqres.in 中的数据