1

I have a jquery autocomplete which is not doing anything. I have used the code from here. It works in their example.

There are some changes... First, array is created from a viewModelList and it works. here is a small part of it:

               var suburbs = [
       {
           id: "17023",
           suburb: "Epsom",
           postCode: "3551",
           state: "VIC"
       },
       {
           id: "17024",
           suburb: "Muskerry",
           postCode: "3557",
           state: "VIC"
       }

I have endeavoured to use messages to indicate the respose - what it is but even the messages dont work... I cannot even get the response value..

I created a div below the form for the messages and they work having been tested using a click function.. I did try a ".change" function on the "#Suburbs" id and also got nothing..

Here is the code:

    <script>
    (function ($) {
        $(function () {

            var suburbs = [
       @for (var i = 0; i < Model.SuburbAndPostcodesList.Count; i++) {
           <text>{
           id: "@Model.SuburbAndPostcodesList[i].SuburbsAndPostcodesId",
           suburb: "@Model.SuburbAndPostcodesList[i].Suburb",
           postCode: "@Model.SuburbAndPostcodesList[i].PostCode",
           state: "@Model.SuburbAndPostcodesList[i].State.ShortName"
       }@(i == Model.SuburbAndPostcodesList.Count - 1 ? "" : ",")</text>
       }
            ];



            $("#Suburb").autocomplete({
                source: function (req, responseFn) {
                    addMessage("search on: '" + req.term + "'<br/>");
                    var re = $.ui.autocomplete.escapeRegex(req.term);
                    var matcher = new RegExp("^" + re, "i");
                    var a = $.grep(suburbs, function (item , index) {
                        //addMessage("&nbsp;&nbsp;sniffing: '" + item + "'<br/>");
                        return matcher.test(item.suburb);
                    });
                    addMessage("Result: " + a.length + " items<br/>");
                    responseFn(a);
                },

                select: function (value, data) {
                    if (typeof data == "undefined") {
                        addMessage('You selected: ' + value + "<br/>");
                    } else {
                        addMessage('You selected: ' + data.item.value + "<br/>");
                    }
                }
            });

            function addMessage(msg) {
                $('#msgs').append(msg);
            }
        });
    });

</script>

The id "#Suburb" is correct and worked for a simple version of .autocomplete.

EDIT: here is page code for the javascript.. Hope this is what you were after..

      <script src="/lib/jquery/dist/jquery.js"></script>
    <script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
    <script src="/js/site.js?v=EWaMeWsJBYWmL2g_KkgXZQ5nPe-a3Ichp0LEgzXczKo"></script>




<script src="/lib/jquery/dist/jquery.min.js"></script>
<script src="/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
<script src="/lib/jquery-ui/jquery-ui.js"></script>
<script>
    (function ($) {
        $(function () {

            var suburbs = [
       {
           id: "17023",
           suburb: "Epsom",
           postCode: "3551",
           state: "VIC"
       },
       {
           id: "17024",
           suburb: "Muskerry",
           postCode: "3557",
           state: "VIC"
       },

...

       {
           id: "17055",
           suburb: "Bonnet Hill",
           postCode: "7053",
           state: "TAS"
       },
       {
           id: "17056",
           suburb: "Wellington Park",
           postCode: "7054",
           state: "TAS"
       }
            ];



            $("#Suburb").autocomplete({
                source: function (req, responseFn) {
                    addMessage("search on: '" + req.term + "'<br/>");
                    var re = $.ui.autocomplete.escapeRegex(req.term);
                    var matcher = new RegExp("^" + re, "i");
                    var a = $.grep(suburbs, function (item , index) {
                        //addMessage("&nbsp;&nbsp;sniffing: '" + item + "'<br/>");
                        return matcher.test(item.suburb);
                    });
                    addMessage("Result: " + a.length + " items<br/>");
                    responseFn(a);
                },

                select: function (value, data) {
                    if (typeof data == "undefined") {
                        addMessage('You selected: ' + value + "<br/>");
                    } else {
                        addMessage('You selected: ' + data.item.value + "<br/>");
                    }
                }
            });

            function addMessage(msg) {
                $('#msgs').append(msg);
            }
        });
    });

</script>

EDIT2: Here is the div element "suburb" as I think its probably a good idea to see what the autocomplete is working on.

<div class="form-group">
        <label class="col-md-2 control-label" for="Suburb">Suburb:</label>
        <div class="col-md-10">
            <input class="form-control" type="text" data-val="true" data-val-required="A suburb name is required" id="Suburb" name="Suburb" value="Eaglehawk" />
            <span class="text-danger field-validation-valid" data-valmsg-for="Suburb" data-valmsg-replace="true" />
        </div>
    </div>
6
  • In order to make this Minimal, Complete, and Verifiable, it might be good if you posted the output of your razor view, instead of the razor view itself. It is much easier to get help here troubleshooting a javascript issue if people can work exclusively with js/css/html, without having to worry about server-side code. Commented Apr 10, 2016 at 14:23
  • Its pretty large which part.. the javascript? Commented Apr 10, 2016 at 14:24
  • If you read the link I posted about Minimal, Complete, and Verifiable, it might explain in greater detail what is most helpful. In your specific example, what that means is to take just enough out of your code to duplicate the problem you are experiencing. This would probably be your html <input> tag, the .autocomplete() code, and a subset of your autocomplete data. If you can put it in a jsfiddle equivalent, so much the better. Commented Apr 10, 2016 at 14:29
  • Hi David.. added the rendered javascript and four or the elements of the suburbs data.. Commented Apr 10, 2016 at 14:32
  • I have also just added in the <DIV> element as well. Commented Apr 10, 2016 at 14:37

1 Answer 1

2

Okay, a few things:

first: your jQuery .ready() function isn't running at all. You are combining several shorthand and advanced techniques, and they are not working. (More details on this in the comments below) Until you can do some research and get the concepts down, probably better to use the long-hand method, and just do

$(document).ready(function() {
});

Second: when you do $('#Suburb'), that means you have to have an element with id="Suburb" someplace in your document. Your input didn't have that.

Third: your a array that you are returning is an array of objects which your autocomplete won't recognize. You either need to return an array of strings, or an array of objects in this format: { label: "Choice1", value: "value1" }. The easiest way to accomplish this was just to add .map into your existing code, right after the .grep:

        source: function (req, responseFn) {
            addMessage("search on: '" + req.term + "'<br/>");
            var re = $.ui.autocomplete.escapeRegex(req.term);
            var matcher = new RegExp("^" + re, "i");
            var a = $.grep(suburbs, function (item , index) {
                return matcher.test(item.suburb);
            });
            a = $.map(a, function(x){
                return x.suburb;
            });
            addMessage("Result: " + a.length + " items<br/>");
            responseFn(a);
        },

That being said, I have made some mods to your code (making some assumptions) and here is a working fiddle. Sorry, I had already started working on my own fiddle by the time you added yours. It was easier to just continue with the fiddle that I created than it was to modify yours.

Sign up to request clarification or add additional context in comments.

4 Comments

As an aside, the first part is supposed to be (function($) {...})(jQuery);. the (function($) {}) part creates an anonymous function. By adding the (jQuery), it executes the anonymous function, making the $ parameter equal to jQuery. By leaving off the (jQuery), you were creating the anonymous function, but never executing it. Still, you don't really need this, unless you are using another js library that redefines the $ variable.
Inside of that anonymous function, you were using the shorthand for $(document).ready(function() {});. It is described here, with this note: "Experienced developers sometimes use the shorthand $() for $( document ).ready(). If you are writing code that people who aren't experienced with jQuery may see, it's best to use the long form."
Exceptional. I will need to go over it closely and will do so tomorrow. I have upvoted it though..
Thanks, and best of luck. Might also take a look at the layout in my fiddle. Additional <script> tags should go in the html section, not the javascript section. (javascript section shouldn't have any html tags in it at all...it is being automatically inserted into a <script> tag already.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.