Implemented JavaScript to dynamically append a pair of buttons onto a single div element

Looking for guidance on how to combine two buttons in the same div using closures.

var form = [
    {
      type: 'button',
      label: 'Reset'
    },
    {
      type: 'button',
      label: 'Submit'
    }
  ];
for (var i = 0; i < form.length; i++) {
    var obj = form[i];
    var element = document.createElement("div");
    switch (obj.type) {
        case "button":
            var wrapHtml = document.createElement("div");
            var wrapHtmlAttr = document.createAttribute("class");
            wrapHtmlAttr.value = "buttons-group";
            wrapHtml.setAttributeNode(wrapHtmlAttr);
            var button = document.createElement('button');
            var textButton = document.createTextNode(obj.label);
            button.appendChild(textButton);
            wrapHtml.appendChild(button);
            element.appendChild(wrapHtml);

            break;
    }
    var div = document.getElementById("form");
    div.appendChild(element);
  }

Seeking advice on combining the two buttons into one div called buttons-group. Any help or suggestions are appreciated!

Check out an example here

Answer №1

In your code, you have successfully implemented the creation of 2 div.button-group elements within a loop. However, to include both buttons in one div element, it is advised to move the creation of the div outside of the loop.

var element = document.createElement("div"); 

For instance:

var element = document.createElement("div");
var wrapHtmlAttr = document.createAttribute("class");
wrapHtmlAttr.value = "buttons-group";
element.setAttributeNode(wrapHtmlAttr);
for (var i = 0; i < form.length; i++) {
    var obj = form[i];
    switch (obj.type) {
        case "button":         
            var button = document.createElement('button');
            var textButton = document.createTextNode(obj.label);
            button.appendChild(textButton);
            element.appendChild(button);

            break;
    }
    var containerDiv = document.getElementById("form");
    
    containerDiv.appendChild(element);
  }

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

What is the best way to conceal a child element within a hidden tab using jQuery, ensuring it remains hidden until I choose to reveal it?

Let me provide an example to explain this situation: <div id="panel-1"> <input name="a" type="text" /> <input name="b" type="text" /> <input name="c" type="text" /> <div> <div id="panel-2"> <input name="d" ty ...

Storing data from an HTML table into a database using ASP.NET MVC and JQUERY/AJAX

I am currently developing a Point of Sale system using ASP.NET MVC and I have encountered an issue with saving the content of the HTML table that displays all the orders to the database. I attempted to send the data through JSON to the controller, but it s ...

What steps should be taken when a checkbox is unchecked?

Essentially, I have 3 checkboxes. When a button is clicked and the box is checked, each checkbox has a boolean that turns to true. But, is it possible to perform an action when unchecking a checkbox without needing another button to trigger an event first ...

HTML5 Audio using AudioJS may not function reliably when loaded remotely

I have been encountering frustrating issues with loading audio tags for a while now. Despite spending nearly two weeks trying to solve the problems, every fix seems to create another one. My webpage includes an < audio > tag that utilizes audio.js t ...

Centering items within grid columns for optimal alignment

I have successfully designed a contact form using a CSS grid layout that features 4 input fields and a submit button spanning across 2 columns. Two of the input fields take up 1fr of space each, while the remaining two are 1/3 wide. My challenge lies in c ...

Tips for Drawing Lines and Preserving Them When a Condition is Met

I am currently utilizing Node.Js in an attempt to outline objects within an image based on certain conditions being met. My goal is to draw lines around specific portions of the image received from an API response. Whenever the response includes the keywor ...

Iterate through each checkbox within a specific classed div to check for selected options

Is there a way to loop through specific checkboxes with a particular class inside a div without assigning individual IDs to each one? I want to avoid the manual process of adding IDs. Below is the code snippet: JS <script> function calculate() { ...

Display a grid layout containing 5 divs in each row, ensuring that all rows begin and end in the

I need to arrange 5 divs (tiles) on each row in a consistent manner. I attempted to accomplish this by checking for every 5th element and adding an empty div if the count is divisible by 5. However, this approach causes rows to start and end at different ...

`Apply a distinctive color to certain text within the selected text option`

                Does anyone have suggestions on how to create a color highlight with the word "stock" (see image for reference) using CSS, JavaScript, jQuery, or any other language? ...

Using JQuery, retrieve all field values on click, excluding the value of the closest field in each row

I have a dynamic table where each row consists of an input field and a button. I am searching for a simpler way to select all input fields except the one in the current row when clicking the button in each row. All input fields have the same name and the r ...

Is it possible to insert uneditable text in a form field using only CSS?

I'm attempting to create a form input field with a specific format. The field should appear as: The prefix domain.com/username/ should be displayed as non-editable text (and not be submitted as form data), allowing the user to input their desired tex ...

Enhance the appearance of the navbar on mobile devices by customizing the styling in Bootstrap 5

Hi everyone, this is my first time posting a question here so please be gentle :) I recently implemented a script to change the CSS of my navbar when scrolling. window.addEventListener("scroll", function () { let header = document.querySelector(".navbar") ...

Attempting to persist a nested document in MongoDB using mongoose within a Nodejs environment

I attempted to save an address as a nested document in the following format When sending data from the client side, it was formatted like this: const address = JSON.stringify( { addressline1:form.addressline1.value, addressline2:form.addressline2.value, c ...

Create a custom design for a Bootstrap 4 Checkbox without including a label

I'm attempting to customize the appearance of a Bootstrap 4 checkbox without including a label: <div class="form-check"> <input class="form-check-input position-static" type="checkbox" id="blankCheckbox" value="option1"> </div> ...

The loop for setState appears to only execute during the final iteration

My app revolves around friends and events, with each friend hosting specific events. I am trying to extract all the events from every friend in the system. To manage these events, I have declared an 'event' state variable as const [events, se ...

Using jQuery to detect changes in the value of form fields, excluding any changes related to display toggles

Currently, I am in the process of revamping a large form that includes various input fields and dropdown menus. The goal is to submit it via AJAX once a field loses focus but only if the value has been altered. To achieve this, I have set up a jQuery selec ...

Body overflow appears horizontal in Windows Operating System while it works fine in macOS

After implementing the code below from a helpful CSS Tricks article, my element spanned across the full width of the page, stretching beyond its parent's boundaries: width: 100vw; position: relative; left: 50%; right: 50%; margin-left: -50vw; margin- ...

Participating in a scheduled Discord Voice chat session

Currently, I am in the process of developing a bot that is designed to automatically join a voice chat at midnight and play a specific song. I have experimented with the following code snippet: // To make use of the discord.js module const Discord = requ ...

Embrace the presence of null values on the client side

When utilizing the code below, I can determine the location of logged-in users. However, there are some users who do not have a specific location assigned. For example, Administrators are common for all locations. In such cases, how can I set it so that ...

Is there a method in Express to verify which URL a post is being sent to?

At the moment, I am using express to proxy my session creation URL in the following manner: app.post('/sessions', (req, res) => { // Code goes here }) The code that is used for this proxy also needs to be applied to my /confirmation endpoi ...