0

My objective is to perform Auto-Complete feature of the same context in multiple pages/Views, for same input having the same class name (i.e. Client Name to be auto complete for many pages like Create and Edit View and others).

Since I need to call the jquery's autocomplete() in each page, I had written in

Views\Shared_Layout.cshtml

page of my project so the auto complete feature will available where required. The code I had written in _Layout.cshtml is as follows:

<script>
    $(document).ready(function () {
         //common 
         $('.form-control.salescode').autocomplete({
              minLength: 4,
              source: '@Url.Action("GetAccountManager", "AccountManager")',
              select: callBackSalesCodeLookUp
         });
    });
</script>

Then any View (Create or Edit) which requires, the auto-complete feature have this code called:

<script>
    function callBackSalesCodeLookUp(event, ui)
    {
        event.preventDefault();
        var selectedArr = ui.item.value.split("|");
        var accountManagerID = selectedArr[0];
        var accountManagerName = selectedArr[1];

        $('.form-control.salescode').val(accountManagerID);
    }
</script>

However, when I ran the project, I am getting an error for pages which have not having the following code, which is as expected:

    function callBackSalesCodeLookUp(event, ui)
    {
        event.preventDefault();
        var selectedArr = ui.item.value.split("|");
        var accountManagerID = selectedArr[0];
        var accountManagerName = selectedArr[1];

        $('.form-control.salescode').val(accountManagerID);
    }

The error I am getting, is in Chrome as :

jquery-3.1.1.js:3855 Uncaught ReferenceError: callBackSalesCodeLookUp is not defined at HTMLDocument. (Login?ReturnUrl=%2FAccountOpeningRegister%2FCreate:393) at mightThrow (jquery-3.1.1.js:3570) at process (jquery-3.1.1.js:3638)

I want to less the code, and which is the reason I made up something like this. I will be glad to know if there is any better way of coding this.

Thank You

1 Answer 1

1

Check if the function exists in the window before calling it.

<script>
    if (typeof callBackSalesCodeLookUp == 'function') {
         $(document).ready(function () {
              //common 
              $('.form-control.salescode').autocomplete({
                   minLength: 4,
                   source: '@Url.Action("GetAccountManager", "AccountManager")',
                   select: callBackSalesCodeLookUp
              });
          });
    }
</script>
Sign up to request clarification or add additional context in comments.

Comments

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.