yarek
yarek

Reputation: 12044

How to add variable to src source in JS script?

This works:

<script src="chat/script.php?room=1&username=John&draggable=1"></script>

and this does not:

<script>
var username="John";
</script>  
<script src="chat/script.php?room=1&username="+username+"&draggable=1"></script>

Any idea how to fix that ?

Upvotes: 0

Views: 18303

Answers (6)

Shani Yaron
Shani Yaron

Reputation: 21

You can change any element's src using this in your JavaScript:

let myElement = (document.getElementById("myElementHTMLId").src =
"some string" + myVariable + "some string");

Upvotes: 0

S.Serpooshan
S.Serpooshan

Reputation: 7440

Another method is to use document.write method as following:

var username = "John";
document.write( "<script src=\"chat/script.php?room=1&username=" + username 
                + "&draggable=1\"><" + "/script>" );

Note that i have break the </script> part such that it doesn't assumed as end closing tag of your main script block! the \"is used to escape the double quotation mark inside the string.

Upvotes: 0

MrCode
MrCode

Reputation: 64526

The content of the script tag is executed, nothing in its attributes will be executed. You can dynamically add a script tag like so:

var username="John";
var s = document.createElement('script');
s.src = "chat/script.php?room=1&username="+username+"&draggable=1";
documennt.getElementsByTagName("head")[0].appendChild(s);

This creates a new script element, sets the src property, and then inserts it into the HTML <head> tag.

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074295

Well, you can do that using client-side code, but not using HTML:

<script>
var username="John";
var script = document.createElement('script');
script.src = "chat/script.php?room=1&username="+username+"&draggable=1";
document.getElementsByTagName('script')[0].parentNode.appendChild(script);
</script>  

Upvotes: 8

EyasSH
EyasSH

Reputation: 3769

Indeed, your variable username is a JavaScript variable. Outside the <script> tag, HTML doesn't know about it. You would need to insert the <script> tag from within JavaScript. this post describes how to do that.

In your case, it would be:

var my_script = document.createElement('script');
my_script.setAttribute('src','chat/script.php?room=1&username=' + username + '&draggable=1');
document.head.appendChild(my_script);

Upvotes: 3

DanMan
DanMan

Reputation: 11561

Use a server-side language like PHP. That src attribute is not part of the Javascript. Only the code inside the script element.

Upvotes: 1

Related Questions