0

I have a javascript array in an external file:

<script src="assets/players.js"></script>

contents of above array:

window.players = [
"Addison, Jackson",
"Agron, Dmitry",
"Zuccarino, John"
]

I have tried to return the number of records to no avail:

<h3>Sample data file with <script>window.players.length;</script> names:</h3>

What am I doing wrong..?

3
  • Javascript won't just print the result be placing something like that into a location. You need to target something and then give that element the value you wish to display. Example: jsfiddle.net/yokx4c27 Commented Aug 12, 2017 at 1:03
  • what about jquery? Would that work? Commented Aug 12, 2017 at 1:04
  • jQuery is a javascript plugin which is just pre-coded javascript so this is easy to do without having to use the jQuery library. Commented Aug 12, 2017 at 1:07

3 Answers 3

2

If you want to write out the length, than you would need to use document.write

<h3>Sample data file with <script>document.write(window.players.length)</script> names:</h3>

Or you could use DOM methods.

<h3>Sample data file with <span id="count"></span> names:</h3>
<script>
    document.querySelector("#count").innerHTML = window.players.length;
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

Javascript is not a "pre-processed" language, like PHP. Change your code to:

<h3>Sample data file with <span id="output"></span> names:</h3>
<script>document.getElementById("output").innerHTML = window.players.length;</script>

Comments

0

You cannot use template-style coding on the client side. Instead, you need to create any element that you can reference from the script and then manipulate its contents, e.g.

<h3 id="num"></h3>

 <script>
   document.getElementById("num").innerHTML = "Sample data file with " + window.players.length +" names"
 </script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.