Reputation: 76
im having trouble creating buttons dynamically by iterating through a loop. i am fairly new at this so im not sure where im going wrong. here's what i have so far. any advice?
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src='http://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type="text/javascript"></script>
<script src="giphy.js"></script>
</head>
<body>
<div id="buttonDiv"></div>
<div id="gifsAppearHere"></div>
</body>
</html>
var topics = ['bikram', 'yoga', 'vegan', 'vegetarian','nutrition', 'exercise', 'pilates','calisthenics', 'ashtanga', 'vinyasa', 'utkatasana']
for (var i = 0; i < topics.length; i++) {
var buttons = $('<button>'+ topics.text + '</button>')
buttons.append('topics');
}
Upvotes: 2
Views: 5554
Reputation: 356
I'm not entirely sure of what you are trying to do but I this is how I would write that code. This will append 11 buttons with names on them to the body.
I hope this helps!
var topics = ['bikram', 'yoga', 'vegan', 'vegetarian', 'nutrition','exercise', 'pilates','calisthenics', 'ashtanga', 'vinyasa', 'utkatasana'];
for (var i = 0; i < topics.length; i++) {
var button = $('<button>'+ topics[i] + '</button>')
$('.div-with-btns').append(button); /*div that holds your btns*/
}
Upvotes: 0
Reputation: 1727
using inline code
var pages = ['bikram', 'yoga', 'vegan', 'vegetarian', 'nutrition', 'exercise', 'pilates','calisthenics', 'ashtanga', 'vinyasa', 'utkatasana'];
var pageButtons = $('#pageButtons');
for (var i = 0; i < pages.length; i++) {
pageButtons.append('<input type="button" id="button' + i + '" value="' + pages[i] + '"/>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pageButtons">
</div>
Upvotes: 0
Reputation: 1074525
Look again at the documentation. You've used append
, but you wanted appendTo
(easy mistake to make).
append
appends the thing you pass as an argument to the thing you call it on.
appendTo
appends the thing you call it on to the thing you pass as an argument.
Also note that the selector "topics"
looks for an element with the tag name topics
, e.g. <topics>...</topics>
. You may have meant to use a class selector (".topics"
), or an ID selector ("#topics"
).
You've also used topics.text
where I think you meant topics[i]
(perhaps an error when simplifying the code for the question).
Example:
var topics = ['bikram', 'yoga', 'vegan', 'vegetarian', 'nutrition', 'exercise', 'pilates','calisthenics', 'ashtanga', 'vinyasa', 'utkatasana']
for (var i = 0; i < topics.length; i++) {
var buttons = $('<button>'+ topics[i] + '</button>')
buttons.appendTo('#topics');
}
<div id="topics"></div><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 2