I’ve got two separate .js files and depending on the choice that the user makes on the form in the select tag, I want the .js file specific to the user request to be used on the html page.
This is my code:
<script type="text/javascript">
$(document).ready(function(){
if (document.getElementById('analyses').value == 'distance'){
<script src="/static/analysis.js"></script>
}else{
<script src="/static/another.js"></script>
}
});
</script>
The html form:
<form id="eventForm">
<select name="event" id="abc">
<option value="" disabled="disabled" selected="selected">Select Event</option>
<option value="US">US</option>
<option value="UK">UK</option>
<option value="Fr">France</option>
</select>
<select name="analysis" id="analyses">
<option value="" disabled="disabled" selected="selected">Select Analysis</option>
<option value="distance">distance</option>
<option value="other">other</option>
</select>
<input type="submit" id="open" onclick="heading()" value="Start Analysis"/>
Presently it just runs the /static/analysis.js file, regardless of the user selection.
Thanks
EDIT:
<script>
function loadScript(path) {
var head=document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', path);
head.appendChild(script);
}
$(document).ready(function(){
if (document.getElementById('analyses').value == 'distance'){
loadScript("/static/analysis.js");
}else{
loadScript("/static/analysisfdfdf.js");
}
});
</script>
You can use this function to load other JS files dynamically
Usage:
Remember that the script will be asynchronously loaded so you can’t assume that a script is loaded after that line. You would need the loaded script to perform a
callbackas a ready notification