Creating dynamic HTML elements for each section using JavaScript

Is there a way to dynamically add a task (input + label) for each specific section/div when entering the name and pressing the "Add" button?

I attempted to create an event for each button to add a task for the corresponding div of that particular section, but I struggled to implement it. Any solutions for this?

This is the HTML structure:

<section id="1" class="1">
    <div id="div1" class="add-input-label">
        <input type="checkbox" name="checkbox-1" id="checkbox-1">
        <label for="checkbox-1">Test</label>
    </div>
    <div id="btn-div-1" class="btn-div-1">
        <input type="text" id="input-text-1">
        <button id="btn-1" class="btn-add">Add</button>
    </div>
</section>
<section id="2" class="2">
    <div id="div2" class="add-input-label">
        <input type="checkbox" name="checkbox-2" id="checkbox-2">
        <label for="checkbox-2">Test</label>
    </div>
    <div id="btn-div-2" class="btn-div-2">
        <input type="text" id="input-text-2">
        <button id="btn-2" class="btn-add">Add</button>
    </div>
</section>

And here is the Javascript code:

const btn = document.querySelectorAll('.btn-add');
const div = document.querySelectorAll('.add-input-label');

btn.forEach((btn) => {
btn.addEventListener('click', () => {
    div.forEach((div) => {
        let label = document.createElement('label');
        let input = document.createElement('input');
        div.appendChild(input);
        div.appendChild(label);
        label.innerText = 'hey';
        input.type = 'checkbox';
    });
});

});

Upon clicking the button, the task is added to both sections. How can I make it so that only the specific section is affected when its respective button is clicked?

Answer №1

Here are a couple of adjustments you can make to your code in order to achieve the desired outcome.

  1. Utilize the forEach method with the index syntax. By incorporating the index i in btn.forEach((btn,i), you can easily differentiate between button indexes.
  2. Avoid using an additional forEach loop for the div. Instead, within the button click listener, utilize the previously obtained button index to ensure that the appendChild function is applied to the correct div.

const btn = document.querySelectorAll('.btn-add');
const div = document.querySelectorAll('.add-input-label');
btn.forEach((btn,i) => {
  btn.addEventListener('click', () => {
      let label = document.createElement('label');
      let input = document.createElement('input');
      div[i].appendChild(input);
      div[i].appendChild(label);
      label.innerText = 'hey';
      input.type = 'checkbox';
  });
});
<section id="1" class="1">
    <div id="div1" class="add-input-label">
        <input type="checkbox" name="checkbox-1" id="checkbox-1">
        <label for="checkbox-1">Test</label>
    </div>
    <div id="btn-div-1" class="btn-div-1">
        <input type="text" id="input-text-1">
        <button id="btn-1" class="btn-add">Add</button>
    </div>
</section>
<section id="2" class="2">
    <div id="div2" class="add-input-label">
        <input type="checkbox" name="checkbox-2" id="checkbox-2">
        <label for="checkbox-2">Test</label>
    </div>
    <div id="btn-div-2" class="btn-div-2">
        <input type="text" id="input-text-2">
        <button id="btn-2" class="btn-add">Add</button>
    </div>
</section>

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

Ways to prevent my website from being accessed through the Uc Browser

Is there a way to prevent my website from functioning on UC Browser using HTML or JavaScript? ...

transmitting an array from JavaScript to PHP

Struggling with passing an array from JavaScript to PHP for a school assignment. I'm still learning and can't seem to figure out what's missing. Any help would be greatly appreciated. This is the code I've tried: if(bets.length > ...

Laravel route does not receive a parameter sent via Ajax

I am currently using Laravel 5.8 and implementing a discount code system on my website. To achieve this, I attempted to send data via Ajax in the following manner: $.ajax({ type: 'POST', url: baseurl + 'discount/register', ...

Rotate image in Vue3 using @click

I have a dashboard with a refresh button that I want to rotate 360 degrees every time it is clicked. How can I achieve this rotation effect on the image with each click of the refresh button? Below is the code snippet I have been working on, but it only r ...

Python script using Selenium to only print elements in an HTML page that have a specific class value and print only certain elements based on

I am currently developing a script to automatically test all the free proxies available on The website contains a comprehensive list of all available proxies, and I have successfully made my script extract and display them. However, I only want to display ...

Exploring Heroes in Angular 2: Retrieving Object Information by Clicking on <li> Items

Currently, I am delving into the documentation for an angular 4 project called "Tour of Heroes" which can be found at https://angular.io/docs/ts/latest/tutorial/toh-pt2.html. <li *ngFor="let hero of heroes" (click)="onSelect(hero)">{{hero.name}}< ...

Node.js and Express: Delivering Seamless Video Streaming via HTTP 206 Partial Content

Having a binary file like an mp4 video in a MarkLogic database, I am utilizing the Node.js API of the database to stream this document in segments. The structure is as follows: html document <video controls="controls" width="600"> <source src= ...

What is the process by which a web browser executes a ".jsx" file while in development?

As a beginner in the world of react, I have successfully been able to execute the dev and build tests. One question that has been boggling my mind is how browsers handle ".js" files. I know that when a project is build, the browser runs the &quo ...

Changing the value of a user object's variable in Django

I have been working on implementing a feature that allows users to edit their personal information in a Django project using Django forms. However, after entering new values in the form and hitting enter, the user is redirected back to the main profile pag ...

Issue alert before running tests on component that includes a Material UI Tooltip

This is a follow-up regarding an issue on the Material-UI GitHub page. You can find more information here. Within my Registration component, there is a button that is initially disabled and should only be enabled after accepting terms and conditions by ch ...

Combining JS and PHP for secure function escaping

Looking for a solution to properly escape quotes in generated PHP Javascript code. Here is an example of the current output: foreach ($array as $element) { echo '<a onClick="myFunctionTakesPHPValues('.$element[0].','.$element[1] ...

Real-time data feeds straight from JSON

Currently, I have a JSON file that is generated dynamically and it contains match information along with a unique id. This JSON data is categorized into live, upcoming, and recent arrays. Being new to Javascript, I am unsure about the best approach to crea ...

The vertical alignment of floated elements in HTML is not correctly positioned

The result of the code is not as expected. The right section should be aligned with the left, but it appears below instead. This is the code I am using: <!-- footer begin --> <footer> <div > ...

Incorporating JSON data into an HTML table

Looking to populate an HTML table with JSON data, but struggling with parsing and appending the data correctly. Can anyone provide guidance or assistance? <!DOCTYPE html> <html> <head> <title>JSON Demo</title> < ...

What is the best way to apply multiple array filters to an object list in react.js?

Looking to filter an array of items using multiple filter arrays in order to display only the items that match all selected filters. For example: The main array contains a table with the following data: ID TypeID LocationID Name 1 2 ...

Looking for subsequence in dropdown choices with no assigned values

I need assistance with searching for a specific substring within text that is fetched from options generated by MySQL. How can I retrieve the selected option's text value in order to search for my desired substring? $(document).ready(function() { ...

In jqGrid's gridComplete event, we can use the getRowData method to retrieve the value of a

Seeking guidance on extracting variables from jqGrid getRowData method While iterating through rows, I simply want to retrieve the ID and Phrase column values into separate variables gridComplete: function () { var allRowsInGrid = $('#list'). ...

Error 403: ACCESS DENIED - The server comprehended the inquiry, yet declines to carry it out

Encountering a persistent 403 error when making an AJAX call to an API. This issue is specific to Microsoft Edge, while other browsers like IE, Chrome, Firefox, and Safari work without any errors. The page doesn't utilize bootstrap, as there have be ...

Switch between input and the input is not displayed inline

I've been struggling to align the Toggle button with the input box for quite some time now. I really need them to be inline so that they form a grid properly as everything is dynamic. I have experimented with using a Div on its own instead of a label ...

Laravel Tutorial: Utilizing for and foreach Loops to Showcase Data in Blade Template

I am trying to use a for and foreach loop to display data based on a template table. However, I am running into an issue where the else conditions always display an index of their own. My expectation is as follows: https://i.stack.imgur.com/tqDSn.png Th ...