Guide on how to attach an external JavaScript file on button click event

How can I execute a JavaScript function from an external JS file by utilizing the onClick event on a button within the file named form.tmpl.htm?

  <button type="button" value="Submit" onClick="Call the external js file" >

The JavaScript file is located in Public/Scripts/filename.js. My template file resides in template/form.tmpl.html. The main directory contains folders named Public and template.

Answer №1

After reading the comments above, I have to agree that while you can't directly call a file in JavaScript, you can load a JS file using a different method. It might not completely address your question, but it could provide some assistance. In my example, I decided to use a link instead of a button...

<a href='linkhref.html' id='mylink'>click me</a>

<script type="text/javascript">

var myLink = document.getElementById('mylink');

myLink.onclick = function(){

    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "Public/Scripts/filename.js."; 
    document.getElementsByTagName("head")[0].appendChild(script);
    return false;

}


</script>

Answer №2

If you wish to have your button trigger the function you've written in filename.js, you need to modify filename.js so that the code you want to execute is wrapped inside a function. Remember, you can only call a function, not a source file (which lacks an entry point).

For example, if your current filename.js contents are:

alert('Hello world');

You should update it to look like this:

function functionName(){
alert('Hello world');
}

Next, remember to include the filename.js in the header of your HTML page using this line:

<head>
<script type="text/javascript" src="Public/Scripts/filename.js"></script>
</head>

This way, you can now invoke the function from filename.js with your button:

<button onclick="functionName()">Call the function</button>

To demonstrate how this works, I've created a basic example. An HTML page prompts the user to enter their name, and upon clicking the button, the function within Public/Scripts/filename.js is called with the inputted string as a parameter. This triggers a popup message saying "Hello, <insertedName>!".

Here's the sample HTML page:

<html>

<head>
<script type="text/javascript" src="Public/Scripts/filename.js"></script>
</head>

<body>
What's your name? <input  id="insertedName" />
<button onclick="functionName(insertedName.value)">Say hello</button>
</body>

</html>

And here's the content of Public/Scripts/filename.js:

function functionName( s ){
alert('Hello, ' + s + '!');
}

Answer №3

When you load the .js file before using the onclick function, it simplifies the coding process and makes it clear what is happening. Let's name the JS file zipcodehelp.js.

Here's the HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Button to Trigger JS Function.</title>
</head>
<body>
    <h1>Click Button to Run Function in '.js' File.</h1>
    <script type="text/javascript" src="zipcodehelp.js"></script>
    <button onclick="ZipcodeHelp();">Get Zip Help!</button>
</body>
</html>

The content of zipcodehelp.js is :

function ZipcodeHelp() {
  alert("If Zipcode is missing in list at left, do: \n\n\
    1. Enter any zipcode and click Create Client. \n\
    2. Goto Zipcodes and create new zip code. \n\
    3. Edit this new client from the client list.\n\
    4. Select the new zipcode." );
}

I hope this explanation is beneficial! Cheers!

–Ken

Answer №4

I managed to accomplish this task successfully by following the example set by Mike Sav. In order for it to work as intended, make sure that there is an external test.js file located in the same folder.

Check out the code snippet from example.html below:

<html>
<button type="button" value="Submit" onclick="myclick()" >
Click here~!
<div id='mylink'></div>
</button>
<script type="text/javascript">
function myclick(){
    var myLink = document.getElementById('mylink');
    myLink.onclick = function(){
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = "./test.js"; 
            document.getElementsByTagName("head")[0].appendChild(script);
            return false;
    }
    document.getElementById('mylink').click();
}
</script>
</html>

And here's the content of test.js:

alert('hello world')

Answer №5

Here is a simple way to accomplish this task.

If you have a JavaScript file called myscript.js in your root directory, you can reference it in the head section of your HTML file like this:

<script src="~/myscript.js"></script>

The content of the JS file (myscript.js) looks like this:

function awesomeClick(){
  alert('awesome click triggered');
}

And here is how you can use it in your HTML code:

<button type="button" id="jstrigger" onclick="javascript:awesomeClick();">Submit</button>

Answer №6

It is recommended to load all your scripts within the head tag while encapsulating the script actions within function braces. Furthermore, ensure that you adjust the scope of variables if they are utilized outside of the script.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensuring session data is updated when saving a mongoose model

I am facing a challenge with updating express session data in the mongoose save callback. Is there a way to access and modify the session data from within line 4 of the code? app.get('/', function(req, res){ var newModel = new Model(somedata); ...

Multiple Button Triggered jQuery Ajax Function

I'm currently working on a project where I retrieve data from MySQL to create 4 buttons. I am using jQuery/ajax to trigger an event when any of the buttons are clicked. However, only the first button seems to be functioning properly, while the other t ...

In Internet Explorer 8, angular's $window service may sometimes return undefined

I've developed a custom directive called slideshow with some scope variables that are two-way bound to ng-style. This directive functions as a responsive carousel that adjusts based on the window height retrieved using the $window service. During tes ...

Is this specific JavaScript function classified as recursive?

Uncertain about the recursive nature of this function. var capitalizeWords = function(input) { var results = []; if(typeof input === 'string'){ return input.toUpperCase(); }else{ input.forEach(function(word){ ...

Floating navigation bar that appears and disappears as you scroll

My webpage has a dynamic navbar that consists of two parts: navbarTop and navbarBottom. The navbarTop should appear when the user has scrolled down more than 110 pixels, while the navbarBottom should show up when the user scrolls up. The issue I am facing ...

React error due to setting div scroll height on component mount

In my code, there is a special div/container that contains multiple <p/> tags. The container has a reference called divRef, which is initially set to null using the useRef function. <div ref={divRef} style={styles.messageListContainer}> ...

Notify the user with a message that our support is limited to Chrome, Firefox, and Edge browsers when utilizing Angular

How can I display a message stating that we only support Chrome, Safari, Firefox, and Edge browsers conditionally for users accessing our site from other browsers like Opera using Angular 10? Does anyone have a code snippet to help me achieve this? I atte ...

Is there a way for me to dynamically decide whether to use the append or prepend function?

Utilizing jQuery to retrieve data from the controller and populate a calendar represented by a table with days in columns. Implementing functionality for navigating between previous week / next week, as well as previous day / next day. The four scenarios s ...

The function array.filter is returning the complete object rather than a single value

I'm facing an issue with a function that filters an array. My goal is to retrieve only the string value, not the entire object. However, I keep getting back the entire object instead of just the string. Interestingly, when I switch the return state ...

Unlocking the power of Google Feed API to incorporate MIXED FORMAT in AngularJS

Currently, I am utilizing Google's Feed API in conjunction with AngularJS to retrieve my feed data in a mixed format of both JSON and XML. Although I have attempted to modify the method and callback tags to MIXED_FORMAT as per Google's documentat ...

Unable to pass data from a Jquery ajax request to another function

I've written a basic ajax request using jQuery. Here is the code for my ajax function: var sendJqueryAjaxRequest = function(arrParams) { var request = $.ajax({ url: arrParams['url'], async: false, ...

I seem to be encountering an issue while looping through an array of objects. Instead of retrieving all two elements, only one object is being returned. Can

Just a heads up, I'm new to coding so please bear with me. I'm attempting to run through the "diary" array and the function "howMany" is only showing 2 'Home' elements, although there are actually 4 'Home' elements in total i ...

Tips for adding text dynamically to images on a carousel

The carousel I am using is Elastislide which can be found at http://tympanus.net/Development/Elastislide/index.html. Currently, it displays results inside the carousel after a search, but I am struggling to dynamically add text in order to clarify to use ...

What is the process for exporting MYSQL data within a specific date range using Laravel?

I have been struggling with a problem that might seem simple to some of you. I am able to filter out data based on a date range and display it in the view. However, I now need to export these searched/filtered results in CSV/Excel format. It would be incr ...

Mistakes related to using FBXLoader in Three.js

I recently delved into the world of three.js and decided to follow a helpful tutorial on loading GLTF Models using Three.js. Excited to further my skills, I wanted to experiment by utilizing the FBX loader to import and animate models from Mixamo. The tut ...

Tips for incorporating conditions when updating data in MongoDB

I am looking for assistance with updating the secondary phone number in the code below. I want to update it only if a 10-digit number is passed from the web form; otherwise, I would like to use the already inserted phone number during the insert operation. ...

Transferring a JSON-encoded string in "windows-1251" format from Python to JavaScript

What I need help with can be best exemplified with a code snippet. Before, I had the code below: content = u'<?xml version="1.0" encoding="windows-1251"?>\n' + ... # with open(file_name, 'w') as f: f.write(content.enco ...

Executing a javascript file inside a jade document

I need help incorporating a JavaScript file into my Jade file so that it runs every time the page is accessed. How can I achieve this? Here is my current code snippet: doctype html html head title= title body h2 Bus Driver Locati ...

What is the process for submitting a form from a different webpage?

I am working on a website with two pages. Each page has a header with navigation tabs to move between page 1 and page 2. When a tab is clicked, I want the selected page to re-POST to the server for a quick refresh before displaying. There is a form on e ...

Function being called by Intersection Observer at an inappropriate moment

After running the page, the intersection observer behaves exactly as desired. However, upon reloading the page, I am automatically taken back to the top of the page (which is expected). Strangely though, when the viewport interacts with the target elemen ...