Ernest Soo
Ernest Soo

Reputation: 194

Load html template script on button click

I have a template <script> in my html:

 <script>
         window.daySelected = window.currentdate;
         window.monthSelected = window.currentmonth;
         window.yearSelected = window.currentyear;
 </script>

Here is an example of an external script file loading on a click event: Jquery load script on click event.

Is there a way to load the template script in my html on a click event?

Upvotes: 1

Views: 1655

Answers (2)

nick zoum
nick zoum

Reputation: 7285

If you want to run a whole javascript file do this

var script = document.createElement("script");
script.src = "url"; // replace url with actual url of script
document.head.appendChild(script);

To add a small script from string form

var script = document.createElement("script");
script.innerHtml = "script"; // replace script with actual script
document.head.appendChild(script);

You could also just create a function

function onClick() {
    // insert your code
}

And you can call it by doing onClick(); using JavaScript

You can also call it from a button by doing <button onclick="onClick()">Click Me</button>

Finally you can also call it from a anchor element by doing <a href="javascript:onClick()">Click Me</a>

Upvotes: 1

jafarbtech
jafarbtech

Reputation: 7015

Create a script element and append it into your head tag like the following

function addVals() {
  var sc = document.createElement("script");
  sc.innerHTML = "window.daySelected = window.currentdate; window.monthSelected = window.currentmonth; window.yearSelected = window.currentyear;";
  document.head.appendChild(sc);
}
<input type="button" onclick="addVals()" value="click me" />

Upvotes: 2

Related Questions