0

I'm building an ajax response and facing a problem. I want to iterat over a array in JS and render an each element with a different URL, but the URL is not changing with every element inside the array. Here's my example and code:

transcript_list = ['first_element_value','second_element_value']
var len = transcript_list.length

for (var i = 0; i < len; i++) {
  $(".transcript").append('<a href = /web_data/output/' + transcript_list[i] + '>' + transcript_list[i] + '</a>' + '|');
} 

If I have two elements in the array I can get the first url as

/web_data/output/first_element_value

but for second url on second element I can only get the URL as

/web_data/output/

which missing the second_element_value at the end of the URL. Can't figure out what is going on.

5
  • 2
    What are transcript_list and len? Commented Aug 19, 2022 at 16:32
  • 3
    And what is len? Not strictly related (depending on the real values in the strings) but IMO HTML attribute value strings should be quoted to avoid potential issues. Commented Aug 19, 2022 at 16:34
  • Does "iter" mean "iterate over"? Please use full words. Commented Aug 19, 2022 at 16:35
  • Once the code is fixed (replace transcript_list with transcript, use transcript.length instead of len) it works fine. I have put the fixed code into an answer as a snippet; this allows people to experiment easily. Commented Aug 19, 2022 at 16:37
  • thanks for your suggest and I will try then all, and for len that my fault that i missed that i have alread writen line above : var len = transcript_list.length Commented Aug 19, 2022 at 17:36

1 Answer 1

1

Once the code is fixed it appears to work fine:

transcript = ['first_element_value','second_element_value']

for (var i = 0; i < transcript.length; i++) {
  $(".transcript").append('<a href = /web_data/output/' + transcript[i] + '>' + transcript[i] + '</a>' + '|');
} 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="transcript"></div>

A slightly-cleaner version might read:

transcripts = ['first_element_value', 'second_element_value']

const links = transcripts
  .map(t => `<a href="/web_data/output/${t}">${t}</a>`)
  .join('&nbsp;|&nbsp;')

$(".transcript").append(links)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="transcript"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you so much, I'm gonna try this out and see if it works!

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.