NealR
NealR

Reputation: 10669

jQuery autocomplete completely unresponsive

This is my first time really delving into jQuery with my ASP MVC3 intranet app. I need the autocomplete to be able to reference a list of items from a database. I followed the tutorial found here and thought "ok, that looks easy"... and now after implementing the code and researching other methods and bashing my head against the keyboard for at least four hours I'm not anywhere closer to making this work that before I wrote the code.

Here is the code from the view, w/the library declarations as well. FYI - I am taking over this project, so all the other javascript/Ajax you see was written by someone else with more experience than me. I put all the code in this section just in case something else is getting in the way.

<link href="../../Content/jquery-ui-1.9.2.custom.css" rel="stylesheet">

<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">

    $(function () {
       $("#BankName").autocomplete({
          source: '@Url.Action("GetBanks", "AgentTransmission")',
          minLength: 1
    });

    $(function () {
        $("#drpProducerType").change(function () {
            var value = $(this).val();
            if (value == "SoleProprietor") {
                $("#Role").val(value);
                $('#DSSfields').removeClass('noSee');
                $('#DSSfields').addClass('seeMe');
                //alert("Role must be set to \"Sole Proprietor\" as well. Monet will do this for you!");
            }
            else {
                //TO DO: add role stuff here as well
                $('#DSSfields').removeClass('seeMe');
                $('#DSSfields').addClass('noSee');
            }

        });
        $("#Role").change(function () {
            var value = $(this).val();
            if (value == "SoleProprietor") {
                $("#drpProducerType").val(value);
                alert("Producer Type changed to \"Sole Proprietor\" as well");
            }

        });
    });


    function ChangeChannel() {
        //this function called if Market Segment changes, to update the channel
        var pendistcode = document.getElementById('Pendist');
        if (pendistcode == null) alert('Error: Cannot find Market Segment control');

        $.ajax({
            type: 'POST',
            url: '/AgentTransmission/GetChannel/',
            data: { pendist: pendistcode.value },
            success: function (data) {
                //                alert("success: " + data);
                $('#channelName').html(data);
                $('#Channel').val(data);
            },
            error: function (data) {
                alert("failure to obtain Channel name");
            }
        });

        CheckTerritory('channel');

    } //end ChangeChannel

    function CheckTerritory(category) {
        //this function called when changes happen that could change the territory (inddist)

        //if the channel changed, or the alignment indicator, update the Territory
        if ((category == "channel") | (category == "align")) UpdateTerritory();

        //only trigger if the state or zip changed on the aligned address 
        if ((category == "L") && ($('#AlignmentL').attr('checked'))) UpdateTerritory();
        if ((category == "M") && ($('#AlignmentM').attr('checked'))) UpdateTerritory();

    } //end CheckTerritory

    function UpdateTerritory() {

        var i = $('#INDDist').val();
        var p = $('#Pendist').val();
       // alert(":" + i + ":" + p + ":");

        //if ((i == "") || (p == "")) return;
        if (p == "") return;

        if ($('#INDDist').val() == "864") {
            $('#INDDist').val("701");
        }
        else {
            if ($('#INDDist').val() == "") {
                $('#INDDist').val("864");
            }
        }
    } //end UpdateTerritory

    function MoreCompanies(row) {
        //if the user clicks on the plus sign, add more company rows
        if (row == '3') {
            $('#plus2').html(' ');
            $('#row3').removeClass('noSee');
            $('#row3').addClass('seeMe');
        }
        if (row == '4') {
            $('#plus3').html(' ');
            $('#row4').removeClass('noSee');
            $('#row4').addClass('seeMe');
        }
        if (row == '5') {
            $('#plus4').html(' ');
            $('#row5').removeClass('noSee');
            $('#row5').addClass('seeMe');
        }

    } //end MoreCompanies

    function CompanyFields() {

    } //end CompanyFields

    function ShowHideTerritory() {
        alert('sunshine');
    } //end ShowHideTerritory

</script>

The text box the autocomplete is supposed to work on

    <div class="M-editor-label">
        Bank\Agency Name
    </div>
    <div class="M-editor-field">
        @Html.TextBoxFor(model => model.BankName, new { id = "BankName" })
        @Html.ValidationMessageFor(model => model.BankName)
    </div>

and here is the GetBanks method from the controller. I've set a breakpoint at the first line of this method and I've never been able to get it to hit.

    //GET
    public JsonResult GetBanks(string search)
    {
        var banks = from c in db.BankListMaster.Where(n => n.BankName.Contains(search))
                        select c.BankName;

        banks = banks.Distinct();

        return Json(banks, JsonRequestBehavior.AllowGet);
    }

EDIT

If I replace the current .autocomplete code with the code suggested by this method instead , I get the following error in Chrome's debugger:

Uncaught Error: cannot call methods on autocomplete prior to initialization; attempted to call method '/AgentTransmission/GetBanks'

Here's the new code, I put it in the exact same spot as what I was previously using:

$(document).ready( function() {
  $('#BankName').autocomplete('@Url.Action("GetBanks", "AgentTransmission")', {
      dataType: 'json',
      parse: function(data) {
          var rows = new Array();
          for(var i=0; i<data.length; i++){
              rows[i] = { data:data[i], value:data[i].BankName };
          }
          return rows;
      },
      formatItem: function(row, i, n) {
          return row.BankName + ' - ' + row.Description;
      },
      width: 300,
      mustMatch: true,
  });
});

Upvotes: 2

Views: 2140

Answers (1)

NealR
NealR

Reputation: 10669

I added an extra set of closing brackets to the autocomplete which cleared this up. The widget functions properly now.

$(function () {
   $("#BankNameAuto").autocomplete({
      source: '@Url.Action("GetBanks", "AgentTransmission")',
      minLength: 1
    });
  }); 

Upvotes: 2

Related Questions