1

I am creating <div>s from a for loop based on user input. So if a user types 10 I want to create 10 <div>s with the text: ITEM 1, ITEM 2, ITEM 3, etc.

var select = $('#dropoptions').val();
var number = $('input').val(); 
$('.result').remove();
for (var i = 0; i < number; i++) {
  container.innerHTML += `<div class="result">ITEM ${select}</div>`; 
}

How can I add number in orders for the created <div>s?

5
  • What do you mean by "add number in orders for created div" ? Commented Jul 18, 2017 at 23:08
  • 1. where does container come from? 2. it's better to append your string into a variable then add it to the container after the loop. 3. number is a string. convert it to a number using parseInt(); Commented Jul 18, 2017 at 23:09
  • when divs are created i want text inside the div to be for first div 1, second 2, third 3 etc @AurelBílý Commented Jul 18, 2017 at 23:10
  • If you wanted "Item {Number}" then you should be using i instead of select, eg ${i+1} Commented Jul 18, 2017 at 23:11
  • 1
    Why do you not use the variable i (or i + 1 for 1 ... n)? Commented Jul 18, 2017 at 23:11

2 Answers 2

3

Just add i in your for loop to the string, like '<div class="result">ITEM' + i + '</div>'

var select = $('#dropoptions').val();
var number = $('input').val(); 
$('.result').remove();
for (var i = 0; i < number; i++) {
  container.innerHTML += '<div class="result">ITEM' + (i + 1) + '</div>'; 
}
Sign up to request clarification or add additional context in comments.

1 Comment

@lejhbah you are welcome, consider accepting the answer, if it helped. Cheers!
0

Here is a working example. You need to make 2 changes:

  1. Change ${select} to (i+1)
  2. (i+1) because it should start from 1 and not 0

container = document.getElementById('container');
var number = 10;
for (var i = 0; i < number; i++) {
  container.innerHTML += '<div class="result">ITEM' + (i + 1) + '</div>';
}
<div id='container'></div>

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.