简体   繁体   中英

Javascript CallBack with same function name in multiple pages

My objective is to perform Auto-Complete feature of the same context in multiple pages/Views, for same input having the same class name (ie 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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM