Is there a way to input a unique number for each array output?

Joined
Aug 31, 2022
Messages
8
Reaction score
0
I attached the file I am working on.
I am trying to number each result so that it says:

City #1 is...
City #2 is...
City #3 is...
... and so on.

I was thinking that I had to write something inside this for loop?

for (var i = 0; i < input.length; i++) {
var a = input;
r = r + "City #" + "???" + "is " + a.value + ("<br>");
}

I am working with Notepad++.
 

Attachments

  • Practice.txt
    1.1 KB · Views: 16
Joined
Mar 11, 2022
Messages
226
Reaction score
32
Embrace your code within the code tags. Noone (or at least me) download ominous txt files from a forum.
 
Joined
Aug 31, 2022
Messages
8
Reaction score
0
I didn't realize text files could be so dangerous.

HTML:
<html>
 
<body style="text-align: center;">
 
    <h2 id="hi">Enter Your Five Favorite Cities</h2>
    <form class="" action="index.html">
        <input type="text" name="favoriteCities[]" value="" /><br>
        <br>
        <input type="text" name="favoriteCities[]" value="" /><br>
        <br>
        <input type="text" name="favoriteCities[]" value="" /><br>
        <br>
        <input type="text" name="favoriteCities[]" value="" /><br>
        <br>
        <input type="text" name="favoriteCities[]" value="" /><br>
    <br>
        <button type="button" name="button" onclick="favoriteCities()">Submit</button>
  
    </form>
 
    <h3 id="hi">Results</h3>
 
    <p id="output"></p>
    
    <script type="text/javascript">
        var r = "";
        function favoriteCities() {
            var input = document.getElementsByName('favoriteCities[]');
 
            for (var i = 0; i < input.length; i++) {
                var a = input[i];
                r = r + "City #" + " " + "is " + a.value + ("<br>");
            }
            document.getElementById("output").innerHTML = r;
        }
    </script>
    
    
</body>
 
</html>
 
Joined
Mar 11, 2022
Messages
226
Reaction score
32
Code:
for (var i = 0; i < input.length; i++) {
                var a = input[i]; var uniqueNumber=i+1;
r = r + "City #" +uniqueNumber+ " " + "is " + a.value + ("<br>");
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,962
Messages
2,570,134
Members
46,692
Latest member
JenniferTi

Latest Threads

Top