Steve Wash
Steve Wash

Reputation: 986

Javascript function not found when moved to external file

I'm moderatley new to ASP.NET and very new to Javascript. I'm writing a ASP.NET UserControl. I had the following:

<head>
<title>Select Asset </title>
<script src="../Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function CheckThenCloseActiveToolTip(supplierID) {
        var radGrid = $find('ctl00_MainContent_SelectAssetGrid1_gridAssetList_ctl00');
        var selectedItems = radGrid.get_masterTableView().get_selectedItems()
        if (selectedItems == null || selectedItems.length == 0) return 'You must select an asset first';
        else {
            DoPartialPostBack('selectasset', selectedItems[0]._dataItem.Id);
            CloseActiveToolTip();
        }
    }

    function PopulateRooms(e) {
        var idx = e.selectedIndex;
        if (idx > -1) {
            var dcId = JSON.stringify({ dataCenterId: e.options[idx].value });
            var pageUrl = '/WebService/AVWebService.asmx';

            $.ajax({
                url: pageUrl + '/GetRooms',
                type: 'post',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: dcId,
                success: OnRoomsReceived,
                error: OnErrorCall
            });
        }
        else {
            var ddlRooms = document.getElementById('MainContent_SelectAssetGrid1_ddlRooms');
            ddlRooms.disabled = true;
            $('#ddlRooms').empty();
            ddlRooms.options[0] = new Option('', '-1');
            getAssets(0);
        }
    }

    function OnRoomsReceived(result) {
        var ddlRooms = document.getElementById('MainContent_SelectAssetGrid1_ddlRooms');
        if (result.d.length > 0) {
            ddlRooms.disabled = false;
            $('#ddlRooms').empty();
            ddlRooms.options[0] = new Option('', '-1');
            for (var i = 0; i < result.d.length; i++) {
                ddlRooms.options[i + 1] = new Option(result.d[i].Name, result.d[i].Id);
            }
        }

        if (result.d.length = 1)
            ddlRooms.selectedIndex = 1;

        getAssets(0);
    }

    function resetGridData() {
        getAssets(0);
    }

    function getAssets(startAt) {
        var cpId = document.getElementById('hfldCompanyId').value;
        var pageUrl = '/WebService/AVWebService.asmx';
        var tableView = $find('ctl00_MainContent_SelectAssetGrid1_gridAssetList').get_masterTableView();
        var ddldc = document.getElementById('MainContent_SelectAssetGrid1_ddlDataCenter');
        var dcIdx = ddldc.selectedIndex;
        var dcId = '';
        if (dcIdx > -1)
            dcId = ddldc.options[dcIdx].value;

        var ddlrm = document.getElementById('MainContent_SelectAssetGrid1_ddlRooms');
        var rmIdx = ddlrm.selectedIndex;
        var rmId = '';
        if (rmIdx > -1)
            rmId = ddlrm.options[rmIdx].value;

        var ddlStatuses = $find('ctl00_MainContent_SelectAssetGrid1_ddlStatuses';

        var rbgAssetClass = document.getElementById('MainContent_SelectAssetGrid1_rbgAssetClass');
        var ac = 0;
        var rbgInputs = rbgAssetClass.getElementsByTagName('input');
        for (var i = 0; i < rbgInputs.length; i++) {
            if (rbgInputs[i].checked) {
                ac = i;
            }
        }

        var filters = [];
        var fbs = document.getElementsByClassName('rgFilterBox');
        for (var i = 0; i < fbs.length; i++)
            if (fbs[i].value != '')
                filters[filters.length] = { field: fbs[i].alt, value: fbs[i].value };

        var params = JSON.stringify({ companyId: cpId,
            startIndex: startAt,
            maximumRows: tableView.get_pageSize(),
            filterExpressions: filters,
            dataCenterId: ddldc.options[ddldc.selectedIndex].value,
            roomId: rmId,
            Statuses: ddlStatuses._checkedIndices,
            assetClass: ac
        });

        $.ajax({
            url: pageUrl + '/GetSelectAssetData',
            type: 'post',
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            data: params,
            success: updateGrid,
            error: OnErrorCall
        });
    }

    function updateGrid(result) {
        var tableView = $find('ctl00_MainContent_SelectAssetGrid1_gridAssetList').get_masterTableView();
        tableView.set_dataSource(result.d.gridData);
        tableView.dataBind();
        tableView.set_virtualItemCount(result.d.count);
    }

    function gridAssetList_Command(sender, args) {
        args.set_cancel(true);

        var pageSize = sender.get_masterTableView().get_pageSize();
        var currentPageIndex = sender.get_masterTableView().get_currentPageIndex();
        if (args.get_commandName() == 'Filter')
            currentPageIndex = 0;

        getAssets(pageSize * currentPageIndex);
    }

    function gridAssetList_Created(sender, args) {
        var fbtns = document.getElementsByClassName('rgFilter');
        for (var i = 0; i < fbtns.length; i++)
            fbtns[i].style.visibility = 'hidden';

        var fbs = document.getElementsByClassName('rgFilterBox');
        for (var i = 0; i < fbs.length; i++)
            fbs[i].onkeypress = applyFilter;
    }

    function applyFilter(args) {
        if (args.keyCode == 13)
            resetGridData();
    }

</script>

This works most of the time, but if I'm loading the UserControl using Page.LoadControl(), it didn't always load the scripts correctly. For a couple of reasons (maybe poor ones) I thought I'd move the scripts to an external file.

<script src="../Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="../Scripts/SelectAsset.js" type="text/javascript"></script>

There's no additional code or setup in the .js file, just

function CheckThenCloseActiveToolTip(supplierID) {
    var radGrid = $find('ctl00_MainContent_SelectAssetGrid1_gridAssetList_ctl00');
    var selectedItems = radGrid.get_masterTableView().get_selectedItems()
    if (selectedItems == null || selectedItems.length == 0) return 'You must select an asset first';

...

But now I get a RunTime error that "function gridAssetList_Command" us undefined. That function is bound to a grid's OnCommand event in the page .

When I examine the page in Firebug, it doesn't list my .js file in the list of script files.

I'm loading my scripts in the . I didn't change them, just moved them. What am I missing?

MORE INFO:


It appears to be using different ClientIds when adding the functions to the controls. The error I'm getting drops be in a dynamic resource with the following:

Sys.Application.add_init(function() {
$create(Telerik.Web.UI.RadGrid, {"ClientID":"ctl00_MainContent_ctl03_gridAssetList","ClientSettings": ...

I'm going to try changing referenes to getElementByClass()

Upvotes: 0

Views: 1348

Answers (2)

Habibillah
Habibillah

Reputation: 28695

The best way to add javascript reference on asp.net web form is using ScriptManager on parent element or parent page such as a Master Page, And use ScriptManagerProxy on content pages and user controls.

Try use ScriptManager or combination of both to resolve your problem. Also use root application alias (~) for refer to file ex. src="~/Scripts/jquery-1.9.1.min.js"

So for simple way change your script reference to become:

<asp:ScriptManager ID="ScriptManagerProxy1" runat="server">
    <Scripts>
        <asp:ScriptReference Path="~/Scripts/jquery-1.9.1.min.js" />
        <asp:ScriptReference Path="~/Scripts/SelectAsset.js" />
    </Scripts>
</asp:ScriptManager>

Update:

use for example:

  • $('table[id*="gridAssetList"]') for table with id = ctl00_gridAssetList_xx
  • $('input[id*="inputTxt"]') for input with id = ctl100_inputTxt
  • etc

to call html tag that rendered by asp.net component using jquery selector.

Upvotes: 1

Chandru  velan
Chandru velan

Reputation: 146

hi steve i think its shows error due to script source path please check that first then to verify the script loaded or not try this below code

if(typeof(yourfunction_name=='function') { // this code will make sure that the function is present in the page //function exits do your functionality. }else { alert('Script not loaded'); }

Upvotes: 0

Related Questions