[RESOLVED]Calling JavaScript from an external file

I am sure that calling a JavaScript function from an external file is basic stuff, but I cannot figure it out.  I am a Asp.Net VB programmer.  

I use script in my .aspx file as a search function to find a record in a list box.  (ListBox1)  It works by typing in the first one or two letters of the data record in a text box.  (txtSearch) This is included in the text box:

<asp:TextBox ID="txtSearch" runat="server" onkeyup = "FilterItems(this.value)" Width="127px"></asp:TextBox>

It works really well using this JavaScript:

<script type = "text/javascript">var ddlText, ddlValue, ddl;function CacheItems()

{ddlText = new Array(); ddlValue = new Array(); ddl = document.getElementById("<%=ListBox1.ID %>");
for (var i = 0; i < ddl.options.length; i++)
{ddlText[ddlText.length] = ddl.options[i].text; ddlValue[ddlValue.length] = ddl.options[i].value;}}
window.onload = CacheItems; function FilterItems(value)
{ddl.options.length = 0; for (var i = 0; i < ddlText.length; i++) {if (ddlText[i].toLowerCase().indexOf(value) != -1)

{AddItem(ddlText[i], ddlValue[i]);}}}
function AddItem(text, value)
{var opt = document.createElement("option"); opt.text = text; opt.value = value; ddl.options.add(opt);}

It is a mystery to me how it does because the text box is not referenced in the script, but that is not my question.  I have multiple pages that duplicate the same script.  What I would like to learn how to do is to put the script in an external file (or
JS folder) and call the script in each .aspx page.  My only motivation for this is to increase loading time.  (I do put the script at the end of the page, so maybe this does not matter.)

PS – I have looked at many examples, but I just don’t get it.  If anybody could give me the specifics to make this work, I would greatly appreciate it.



Hi Carthalion,

From your description, If you want to use external JS files, you could put the the JavaScript code into the JS file, then add script references. You could refer to the following code.

Code in Page (.aspx)

    <script src="MyTestJs.js"></script>
        <a onclick="SayHello();" >Click Me</a>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

Code in Page (MyTestJs.js)

function SayHello() {
    var item = document.getElementById("TextBox1");
    item.value = "HH";

Actually, when we use external .js file, the server tags won’t work in javascript files. So, we can directly access the element by its ID like above code.

Best Regards,

Leave a Reply