I’m trying to dynamically change the <script src=oldValue”/> InputValue depends on what user types in input and after submitting page will reload with new <script src=newValue”/>
JavaScript
x
6
1
<input type="text" id="text" />
2
<input type="button" id="btn" value="Submit" onClick="javascript: window.open('http://www.mywebsite.com/print/' + document.getElementById('text').value);" />
3
4
5
<script src="//script.ashx?company=InputValue" async></script>
6
Advertisement
Answer
The first example changes the src attribute for the script element. The second example is inserting a new script element. I don’t know what would work best in your case.
The first example:
JavaScript
1
7
1
document.forms.test.addEventListener('submit', e => {
2
e.preventDefault();
3
var new_script = e.target.script.value;
4
var script_elm = document.scripts.customscript;
5
script_elm.src = `/script.ashx?company=${new_script}`;
6
console.log(script_elm);
7
});
JavaScript
1
5
1
<form name="test">
2
<input name="script" type="text" />
3
<button>Add script</button>
4
</form>
5
<script name="customscript" async></script>
The second example:
JavaScript
1
8
1
document.forms.test.addEventListener('submit', e => {
2
e.preventDefault();
3
var script_elm = document.createElement('script');
4
script_elm.async = true;
5
script_elm.innerText = 'function testing(){alert("testing")};';
6
document.body.append(script_elm);
7
testing();
8
});
JavaScript
1
3
1
<form name="test">
2
<button>Add script</button>
3
</form>