Reputation: 219
I have defined a variable in a function which stores a value provided by a 'data' attribute in a tag.
I.e. <img data-value="##"/>
(## denoting a number from 1 - XX).
I have stored this variable as such:
$dataValue = $('img').attr('data-value');
I now want to use $dataValue
variable to append all <img>
tags with all the values. For example, given the data-value is 4, the output would be:
<img src="http://placehold.it/50x50?text=1" />
<img src="http://placehold.it/50x50?text=2" />
<img src="http://placehold.it/50x50?text=3" />
<img src="http://placehold.it/50x50?text=4" />
I have done the below so far, but I am not able to figure out a way to increment over the number '4' (or whatever number the data-value is) and spit out 4 image tags in incremental order as shown above.
var img = '<img src="http://placehold.it/50x50?text=' + $dataValue + '" />';
// <img src="http://placehold.it/50x50?text=4" />
How do I achieve the output above so that all numbers starting from 1 are logged up till the data-value number. I want to use these to then append these tags to another place.
Upvotes: 1
Views: 83
Reputation: 7593
A basic loop is all you need
var dataValue = $('img').data('value');
for (i = 1; i <= dataValue; i++) {
$('.container').append('<img src="http://placehold.it/50x50?text=' + dataValue + '" />')
}
Where $('.container')
is the name of the element you want to append the images.
Also, I suggest you get the dataValue using .data()
instead of .attr()
as .data() is made just for that.
Also keep in mind that .append()
can be changed for other methods such as .before()
, .after()
, .prepend()
, etc. I suggest you read up on the method you need.
Upvotes: 2