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”/>
<input type="text" id="text" /> <input type="button" id="btn" value="Submit" onClick="javascript: window.open('http://www.mywebsite.com/print/' + document.getElementById('text').value);" /> <script src="//script.ashx?company=InputValue" async></script>
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:
document.forms.test.addEventListener('submit', e => { e.preventDefault(); var new_script = e.target.script.value; var script_elm = document.scripts.customscript; script_elm.src = `/script.ashx?company=${new_script}`; console.log(script_elm); });
<form name="test"> <input name="script" type="text" /> <button>Add script</button> </form> <script name="customscript" async></script>
The second example:
document.forms.test.addEventListener('submit', e => { e.preventDefault(); var script_elm = document.createElement('script'); script_elm.async = true; script_elm.innerText = 'function testing(){alert("testing")};'; document.body.append(script_elm); testing(); });
<form name="test"> <button>Add script</button> </form>