Utilizing a for loop in jQuery or JavaScript to dynamically generate buttons

I'm struggling with dynamically creating buttons through a loop. I am new to this, so I'm not sure where I'm making a mistake. Here is what I have so far. Any suggestions?

<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'); 
} 

Answer №1

Take another look at the documentation. You used append, when you actually needed to use appendTo (an easy mistake to make).

append adds the element you provide as an argument to the specified element.

appendTo adds the element you call it on to the element provided as an argument.

It's important to remember that the selector "topics" searches for an element with the tag name topics, like <topics>...</topics>. You might have intended to use a class selector (".topics") or an ID selector ("#topics").

You also referenced topics.text where I believe you meant topics[i] (a possible error when simplifying the code for the question).

For instance:

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>

Answer №2

using code directly in the content

var websites = ['google', 'youtube', 'facebook', 'twitter', 'linkedin',   'instagram', 'reddit','pinterest', 'tiktok', 'snapchat', 'amazon'];
var webButtons = $('#webButtons');
for (var j = 0; j < websites.length; j++) {
  webButtons.append('<input type="button" id="button' + j + '" value="' + websites[j] + '"/>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="webButtons">

</div>

Answer №3

Not completely certain about your intentions, but here is my take on the code. This snippet will add 11 buttons with different names to the body of your webpage.

Hopefully, this solution works for you!

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); /*container for buttons*/ 
} 

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with connecting static files in express.js

Hey there! I'm having an issue with the redirect not working when I click the "Submit" button on the login page. The code in my index.js file looks like this: app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static(path.join(__dir ...

Ajax is invoked only one time

The system is set up to display a follow button and an unfollow button. Clicking the follow button should make the unfollow button appear, and vice versa. Currently, when you click "follow", the database updates and the follow button disappears while the ...

Issues with integrating React-Bootstrap onto components

Just started working on a new React application and decided to incorporate react-bootstrap. After running npm install react-bootstrap bootstrap, I noticed that the Column, Row, and Button tags were not functioning properly even though the react-bootstrap ...

Passing input parameters from a jQuery dialogue box to a handler file (.ashx) in ASP.NET: A step-by-step guide

Hey everyone! I've set up a jQuery dialog box with two input fields as shown below: <div id="dialog" title="Login"> <form action="" method="POST" id="loginForm"> Username: <input type="text" name="username" /><b ...

The mark-compacts were not efficient enough, they approached the heap limit and as a result, the allocation failed. The JavaScript

Currently working with Angular version 7.2 and encountering an issue when running ng serve: FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory What does this error mean? How can it be resolved? The ...

Retrieve mongodb objects that fall within a specified date range

Within my collection, there is an example document structured as follows: { "_id" : ObjectId("5bbb299f06229dddbaab553b"), "phone" : "+38 (031) 231-23-21", "date_call" : "2018-10-08", "adress_delivery" : "1", "quantity_concrete" : "1", ...

Adjust focus dynamically on pressing enter in an HTML form

I am currently working on adjusting the functionality of my HTML input form to change focus upon pressing the enter key. I need to trigger the saveValue() function from the input field when the enter key is pressed and then move the focus to the next input ...

What is the process for converting an Angular UTC timestamp to a local timestamp?

Is it possible to convert a UTC timestamp to a local time timestamp using any function or method? I am sending the timestamp to angular moments, but the server's timestamp is in UTC. ...

Refresh Google Maps without showing gray areas on the screen

Currently, I am utilizing the Google Maps API v3 in javascript and frequently reloading the map using an app.get while also incorporating layers and bookmarks via mongodb. Whenever I reload the map to erase everything, a gray background appears in the div ...

Toggle the visibility of one div while hiding another by checking a checkbox

When checkbox1 is checked, I want to hide div1 and show div2. I've attempted the code below, but it didn't work as expected. <script type="text/javascript"> function valueChanged() { if ($('.checkbox1').is(":checked" ...

Enhancing the background of a website with the power of CSS

I am looking to create a customized table without the balls/pots in it. The number of rows on the y-axis will vary depending on the number of names I have, and can be more or less. The values on the x-axis are determined by a parameter included in the URL ...

Navigating to an offline HTML webpage using JavaScript in a PhoneGap application

I am currently developing a phonegap application. I am attempting to create a login feature where upon clicking the submit button on the Login.html page, I should be directed to a local HTML file. Login.html <tr> <td>&nbsp;</td> ...

Using the Promise function with callback to map the JSON payload object into an object

I received a JSON payload with the following structure: { "name": "Reports", "subject": "Monthly Reports", "attachments":[ { "attachment":{ "name": "Month1.pdf", "type": "application/pdf", "path": "h ...

Troubleshooting React Native in VS Code using Node shims

I recently started working on a React Native project using the Ignite CLI 2.0.0 default boilerplate, and I find myself in need of some dependencies from node-based packages. To address this, I created files named transformers.js, babel-transform.js, and r ...

Stopping the execution of a request handling function in Express/Node: tips and tricks

I am currently running an Express server that offers some computations as web services. The computation time can vary from less than 1 second to 10 seconds. I am curious if there is a method to halt the execution of a request-handling function (which is ...

Creating a dynamic NxNxN matrix from a basic array in Vue.js

Consider an array: listItems = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ,13 ,14 ,15 ,16, 17, 18, 19, 20, 21, 22, 23]; I would like to transform it into a 3-dimensional Array((Matrix of ROW x COLUMN)x SET according to the number of instances. Here is an exa ...

Utilizing Next.JS and Nodemailer to seamlessly send emails through a contact form

I'm facing an issue with my contact form in next.js. Everything was working fine until I deployed it on Vercel. Although I don't see any errors, I am not receiving emails on my Gmail account after submitting the form. Additionally, I am not getti ...

Creating a Node server exclusively for handling POST requests is a straightforward process

I'm looking to set up a Node server that specifically handles POST requests. The goal is to take the data from the request body and use it to make a system call. However, my current setup only includes: var express = require('express'); var ...

Combine the values of identical keys from multiple objects in an array by utilizing the forEach method in JavaScript

I am currently working on refining a shopping basket function with Vue JS. One of the key features I need to implement is a subtotal calculation that multiplies the price and quantity values for each item and then combines them to create an overall subtota ...

Losing authentication token when refreshing with Nuxt asyncData and Axios

While testing a get API that retrieves an array of mail data through Postman, everything seems to be working smoothly. However, when I implement the asyncData method to fetch the array in my code, it only works once. Upon page refresh, I encounter a 401 er ...