Search code examples
javascriptjquerytypeahead.jsbootstrap-typeaheadhtml-input

Extract more info from themoviedb using typeahead.js and put it in other inputs


I'm using typeahead.js to get movie info from themoviedb api. I need when the user type the movie's title get the year of the movie and the ID of the movie to be added automatically to other inputs.

So when the user using the input Movie title and he click on the suggested titles, It will automatically add the year and the movie id to the other inputs

HTML Code

<input class="typeahead" placeholder="Movie Title Here"><br>
<input class="year" placeholder="Year Here">
<input class="id" placeholder="Year ID">

JS code

Look close to the return (at Line 12) there is the info I need to be transferred to other inputs

var movies = new Bloodhound({
    datumTokenizer: function (datum) {
        return Bloodhound.tokenizers.whitespace(datum.value);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 10,
    remote: {
        url: 'http://api.themoviedb.org/3/search/movie?api_key=470fd2ec8853e25d2f8d86f685d2270e&query=%QUERY&search_type=ngram',
        filter: function (movies) {
            // Map the remote source JSON array to a JavaScript array
            return $.map(movies.results, function (movie) {
                    return {
                        id: movie.id,
                        value: movie.original_title,
                        year: (movie.release_date.substr(0,4) ? movie.release_date.substr(0,4) : '')
                    };
                });
            }
        }
    });

// Initialize the Bloodhound suggestion engine
movies.initialize();

// Instantiate the Typeahead UI
$('.typeahead').typeahead({
    hint: true,
    highlight: true
}, {
    displayKey: 'value',
    source: movies.ttAdapter(),
    templates: {
    empty: [
        '<div class="empty-message">',
        'unable to find any Best Picture winners that match the current query',
        '</div>'
    ].join('\n'),
    suggestion: Handlebars.compile('<p><strong>{{value}}</strong> – {{year}}</p>')
}

});

here is my code in action on jsfiddle to try yourself:

http://jsfiddle.net/Jim_Toth/ss8L24x8/


Solution

  • I've added a way to auto-populate the associated input controls here:

    http://jsfiddle.net/Fresh/cmq80qx3/

    The key part of the code to achieve the auto-population is:

    bind("typeahead:selected", function (obj, datum, name) {
     $('.year').val(datum.year);
     $('.id').val(datum.id);
    });
    

    This code specifies the function which should be called when a typeahead value is selected, in this case it appropriately sets the values of the year and id inputs.