Nilmag
Nilmag

Reputation: 573

Autocomplete not showing/working OdeToFood

I am having some trouble with autocomplete with the OdeToFood pluralsight project. There are results when i use autocomplete in the URL, however when i type into the search bar on my builds homepage nothing happens.

Index.cshtml

@model IEnumerable<OdeToFood.Models.RestaurantListViewModel>

@{
    ViewBag.Title = "Home Page";
}


 <form method="get" action="@Url.Action("Index")" data-otf-ajax="true" data-otf-target="#restaurantList">
    <input type="text" name="searchTerm" data-otf-autocomplete="@Url.Action("Autocomplete")" />
    <input type="submit" value="Search By Name" />
</form> 

@Html.Partial("_Restaurants", Model)

segment of HomeController.cs

public ActionResult Autocomplete(string term)
        {
            var model = _db.Restaurants
                .Where(r => r.Name.StartsWith(term))
                .Take(10)
                .Select(r => new { label = r.Name });
            return Json(model, JsonRequestBehavior.AllowGet);
        }

otf.js

$(function () {

    var AjaxFormSubmit = function () {

        var $form = $(this);
        var options = {
            url: $form.attr("action"),
            type: $form.attr("method"),
            data: $form.serialize()
        };


        $.ajax(options).done(function (data) {
            var $target = $($form.attr("data-otf-target"));
            var $newHtml = $(data);
            $target.replaceWith($newHtml);
            $newHtml.effect("slide");

        });

        return false;
    };

    var submitAutocompleteForm = function (event, ui) {//-------------a5
        var $input = $(this);
        $input.val(ui.item.label);
        var $form = $input.parents("form:first");
        $form.submit();
    };

    var createAutocomplete = function () {
        var $input = $(this);
        var options = {
            source: $input.attr("data-otf-autocomplete"), //---- a2
            select: submitAutocompleteForm //------------a4
        };

        $input.autocomplete(options); //--------------a3
    };

    $("form[data-otf-ajax='true']").submit(AjaxFormSubmit);
    $("import[data-otf-autocomplete]").each(createAutocomplete);
})

I do apologise if it's a stupid mistake, i am fairly new to jquery and i am getting no error results therefore making it hard to find any documentation that may help. Thanks for you time.

Upvotes: 0

Views: 486

Answers (1)

OdeToCode
OdeToCode

Reputation: 4986

I think the problem is this line of code:

$("import[data-otf-autocomplete]").each(createAutocomplete);

This code is telling jQuery to go off looking for an "import" element, but you really want to find an "input" element.

$("input[data-otf-autocomplete]").each(createAutocomplete);

Everything else looks good, I hope that solves the problem.

Upvotes: 2

Related Questions