bassjobsen / Bootstrap-3-Typeahead

The Typeahead plugin from Twitter's Bootstrap 2 ready to use with Bootstrap 3 and Bootstrap 4
1.68k stars 1.33k forks source link

"TypeError: $(...).typeahead is not a function" when using with RequireJS, ok otherwise #106

Open xhanrot opened 9 years ago

xhanrot commented 9 years ago

In my project, I use RequireJS to manage depedencies. And it seems that when using RequireJS, typeahead doesn't work. The console displays the following message : "TypeError: $(...).typeahead is not a function". If I remove RequireJS, everything works fine.

Here are some test files.

HTML (test.html):

<!DOCTYPE html>
<html>
<head><title>Test</title></head>
<body><p>Test</p>

<form id="searchForm"><input id="textSearch" type="text" data-provide="typeahead" autocomplete="off"
                             placeholder="Search"></form>
<script src="/js/bower_components/requirejs/require.js" data-main="/js/dist/test"></script>
</body>
</html>

Javascript (/js/dist/test.js) :

requirejs.config({
  baseUrl: "/js/dist",
  paths: {
    jquery: "../bower_components/jquery/dist/jquery.min",
    typeahead: "../bower_components/bootstrap3-typeahead/bootstrap3-typeahead"
  },
  shim: {
    typeahead: {
      deps: ["jquery"]
    }
  }
});

define(["jquery", "typeahead"], function($) {
  $("#textSearch").typeahead();
});
vagur commented 9 years ago

it's work for me

requirejs.config({
  baseUrl: "/js/dist",
  paths: {
    jquery: "../bower_components/jquery/dist/jquery.min",
    'bootstrap3-typeahead': "../bower_components/bootstrap3-typeahead/bootstrap3-typeahead"
  },
  shim: {

  }
});

define(["jquery", "bootstrap3-typeahead"], function($) {
  $("#textSearch").typeahead();
});

because

define("bootstrap3-typeahead", ["jquery"], function($) { ...

in bootstrap3-typeahead.js

rabinneslo commented 9 years ago

Have you checked that typeahead is exported correctly?

Prakash-shan commented 9 years ago

hi..i have also got the same problem. i have exported that correctly. Still i have the same problem.

rabinneslo commented 9 years ago

Dear Prakash-shan,

You have to make sure to refer to the name that is in the bootstrap3-typeahead.js file in your requirejs configuration. If not please post your abbreviated code so I can have a look.

Regards,

Rabin

surbhi-bhatnagar commented 8 years ago

hi , i am getting the same error even then i have exported the files correctly.For your reference i am posting my code-

main.js code: requirejs.config({ paths: { 'text': '../Scripts/Vendor/text', 'durandal': '../Scripts/Vendor/durandal', 'plugins': '../Scripts/Vendor/durandal/plugins', 'transitions': '../Scripts/Vendor/durandal/transitions', 'knockout': '../Scripts/knockout-3.3.0', 'jquery': '../Scripts/jquery-1.10.1', 'typeahead': '../Scripts/typeahead-0.10.1' } });

define(['durandal/system', 'durandal/app', 'durandal/viewLocator'], function (system, app, viewLocator) { //>>excludeStart("build", true); system.debug(true); //>>excludeEnd("build");

app.title = 'TypeAhead';

//specify which plugins to install and their configuration
app.configurePlugins({
    router: true,
    dialog: true,
    widget: {
        kinds: ['expander']
    }
});

app.start().then(function () {
    //Replace 'viewmodels' in the moduleId with 'views' to locate the view.
    //Look for partial views in a 'views' folder in the root.
    viewLocator.useConvention();

    //Show the app by setting the root view model for our application.
    app.setRoot('shell');
});

});

shell.ts code: /// /// /// /////

import _router = require('plugins/router'); import _app = require('durandal/app'); import refSystem = require('durandal/system'); import _ko = require('knockout'); import _jquery = require('jquery');

class shell { public router: DurandalRootRouter; app = _app; ko = _ko; jquery = _jquery; name: KnockoutObservable = _ko.observable(''); sayHello: () => void; someOptions: KnockoutObservableArray = _ko.observableArray([]); typeAheadName: KnockoutObservable = _ko.observable(''); constructor() { var self = this; self.router = _router; self.name = _ko.observable("test"); self.typeAheadName = _ko.observable('cars'); self.someOptions = _ko.observableArray(['Audi', 'BMW', 'Bugatti', 'Ferrari', 'Ford', 'Lamborghini', 'Mercedes Benz', 'Porsche', 'Rolls-Royce', 'Volkswagen']); self.sayHello = function () { _app.showMessage('Hello ' + self.name() + '! Nice to meet you.', 'Greetings');

    };

}
activate() {
    var self = this;
    self.router.map([
        { route: '', title: 'Home', moduleId: 'home', nav: true },
        { route: 'rainer', title: 'Mount Rainier', moduleId: 'rainer', nav: true }
    ]).buildNavigationModel();

    return self.router.activate();
}

}

//return new shell();

//var shellModule: ShellStatic; //export = shellModule;

export = shell;

and the page in which iam implementing the typeahead:

home.ts code: /// /// /// /////

import _router = require('plugins/router'); import _app = require('durandal/app'); import refSystem = require('durandal/system'); import _ko = require('knockout'); import _jquery = require('jquery'); class home { app = _app; ko = _ko; jquery = _jquery; name: KnockoutObservable = _ko.observable(''); sayHello: () => void; someOptions: KnockoutObservableArray = _ko.observableArray([]); typeAheadName: KnockoutObservable = _ko.observable(''); constructor() { var self = this; self.name = _ko.observable("test"); self.typeAheadName = _ko.observable('cars'); self.someOptions = _ko.observableArray(['Audi', 'BMW', 'Bugatti', 'Ferrari', 'Ford', 'Lamborghini', 'Mercedes Benz', 'Porsche', 'Rolls-Royce', 'Volkswagen']); self.sayHello = function () { _app.showMessage('Hello ' + self.name() + '! Nice to meet you.', 'Greetings');

    };

    _ko.bindingHandlers.typeahead = {
        init: function (element, valueAccessor, bindingAccessor) {
            var substringMatcher = function (strs) {
                return function findMatches(q, cb) {
                    var matches, substringRegex;

                    // an array that will be populated with substring matches
                    matches = [];

                    // regex used to determine if a string contains the substring `q`
                    substringRegex = new RegExp(q, 'i');

                    // iterate through the pool of strings and for any string that
                    // contains the substring `q`, add it to the `matches` array
                    $.each(strs, function (i, str) {
                        // console.log(str);
                        if (substringRegex.test(str)) {
                            // the typeahead jQuery plugin expects suggestions to a
                            // JavaScript object, refer to typeahead docs for more info
                            matches.push({
                                value: str
                            });
                        }
                    });

                    cb(matches);
                };
            };
            var $e = $(element),
                options = ko.unwrap(valueAccessor());

            console.dir(options.source());

            console.dir($e);

            // passing in `null` for the `options` arguments will result in the default
            // options being used
            $e.typeahead({
                highlight: true,
                minLength: 2
            }, {
                    source: substringMatcher(options.source())
                }).on('typeahead:selected', function (el, datum) {
                    console.dir(datum);
                }).on('typeahead:autocompleted', function (el, datum) {
                    console.dir(datum);
                });

        }
    };

}

}

//return new shell();

//var shellModule: ShellStatic; //export = shellModule;

export = home;

home.html:

<!DOCTYPE html>

```

Hello! What is your name?

Type your favorite car name

```

when i try to import the typeahead in any .ts file i am getting error module is not defined.Can u plz help me out.